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

XML对节点操作的问题?
网上找到了一个示例
data.xml的文件,内容如下,
<?xml version="1.0" encoding="gb2312"?>
<Employees>
  <Node genre="李赞红" ISBN="2-3631-4">
  <title>CS从入门到精通</title>
  <author>候捷</author>
  <price>58.3</price>
  </Node>
  <Node genre="李赞红" ISBN="2-3631-4">
  <title>CS从入门到精通</title>
  <author>候捷</author>
  <price>58.3</price>
  </Node>
</Employees>

添加一个结点:

XmlDocument xmlDoc=new XmlDocument(); 
xmlDoc.Load(Server.MapPath("data.xml")); 
XmlNode root=xmlDoc.SelectSingleNode("Employees");//查找<Employees> 
XmlElement xe1=xmlDoc.CreateElement("Node");//创建一个<Node>节点 
xe1.SetAttribute("genre","张三");//设置该节点genre属性 
xe1.SetAttribute("ISBN","1-1111-1");//设置该节点ISBN属性 

XmlElement xesub1=xmlDoc.CreateElement("title"); 
xesub1.InnerText="C#入门帮助";//设置文本节点 
xe1.AppendChild(xesub1);//添加到<Node>节点中 
XmlElement xesub2=xmlDoc.CreateElement("author"); 
xesub2.InnerText="高手"; 
xe1.AppendChild(xesub2); 
XmlElement xesub3=xmlDoc.CreateElement("price"); 
xesub3.InnerText="158.3"; 
xe1.AppendChild(xesub3); 

root.AppendChild(xe1);//添加到<Employees>节点中 
xmlDoc.Save ( Server.MapPath("data.xml") );



这样是可行的.但如果我的data.xml为以下内容就会出错,请问如果是像下面的XML如何添加?
也就是<Employees> 属性多了个suxing="abc"
<?xml version="1.0" encoding="gb2312"?>
<Employees suxing="abc">
  <Node genre="李赞红" ISBN="2-3631-4">
  <title>CS从入门到精通</title>
  <author>候捷</author>
  <price>58.3</price>
  </Node>
  <Node genre="李赞红" ISBN="2-3631-4">
  <title>CS从入门到精通</title>
  <author>候捷</author>
  <price>58.3</price>
  </Node>
</Employees>


------解决方案--------------------
XmlDocument d = new XmlDocument();
XmlElement root = d.CreateElement("Employees");
root.SetAttribute("suxing", "abc");
d.AppendChild(root);
------解决方案--------------------
主要是这个对节点增加属性root.SetAttribute("suxing", "abc");
------解决方案--------------------
多属性就多用几次root.SetAttribute("..", "..");