日期:2014-05-18  浏览次数:20906 次

怎么操作XML文件,求助
using System.Xml;
namespace ModifyXmlDocument1
{
  class ModifyXml
  {
  /* 实现在filename参数为文件名的xml文件中对所有price子元素值按discount打折,
  * 并保存修改的xml文件。*/
  static public void ModifyPrice(string filename, double discount)
  { /*怎么找到所有price子元素*/

}


  /* 在xml文件中删除Title是strTitle参数的Book元素,如果删除成功,保存修改的xml文件,
  * 并将修改的xml输出控制台,返回true,否则返回false,不输出。*/
  static public bool DeleteBook(string filename, string strTitle)
  {
  XmlDocument xmlDoc = new XmlDocument();
  xmlDoc.Load(filename);
  XmlNodeList xnl = xmlDoc.SelectSingleNode("bookstore").ChildNodes;

  foreach (XmlNode xn in xnl)
  {
  XmlElement xe = (XmlElement)xn;
  if (xe.GetAttributeNode("title") == strTitle) /*这里应该怎么写:删除Title是strTitle参数的Book元素*/
  {
  xe.RemoveAttribute("title");//删除genre属性  
  }

  }
  xmlDoc.Save(filename);

  return true;
  }


  /*在xml文件中的bookstore元素最后添加以下book元素,并保存修改的xml文件:
  * <book ,genre="Computer" publicationdate="2008" >
  <title>C++ 程序设计</title>
  <author>
  <name>张文</name>
  </author>
  <price>39.50</price>
  </book>*/
  static public void InsertBook(string filename)
  {
  XmlDocument xmlDoc = new XmlDocument();
  xmlDoc.Load(filename);
  XmlNode root = xmlDoc.SelectSingleNode("bookstore");//查找<bookstore>  
  XmlElement xe1 = xmlDoc.CreateElement("book");//创建一个<book>节点  
  xe1.SetAttribute("genre", "Computer");//设置该节点genre属性  
  // xe1.SetAttribute("ISBN", "2-3631-4");//设置该节点ISBN属性  

  XmlElement xesub1 = xmlDoc.CreateElement("title");
  xesub1.InnerText = "C++ 程序设计";//设置文本节点  
  xe1.AppendChild(xesub1);//添加到<book>节点中  
  XmlElement xesub2 = xmlDoc.CreateElement("author");
  xesub2.InnerText = "张文";
  xe1.AppendChild(xesub2);
  XmlElement xesub3 = xmlDoc.CreateElement("price");
  xesub3.InnerText = "39.50";
  xe1.AppendChild(xesub3);

  root.AppendChild(xe1);//添加到<bookstore>节点中  
  xmlDoc.Save(filename);
  }


  /* 查询filename参数为文件名的xml中book/author/last-name值是lastName参数的Book元素,
  * 返回该book的子元素title值。*/
  static public void Main(string[] args)
  {
  InsertBook("C:\\books1.xml");
  }

  }
}
C:\\books1.xml文件:
XML code
<?xml version='1.0'?>
<!-- This file represents a fragment of a book store inventory database -->
<bookstore>
  <book genre="autobiography" publicationdate="1981" ISBN="1-861003-11-0">
 <ti