日期:2014-05-20  浏览次数:20971 次

如何给指定的element追加一个属性
例如:
<?xml version="1.0">
  <ListSection>
    <ListPart>
      <ListNo>1</ListNo>
      <ListSymbol>test1</ListSymbol>
      <ListComment>test1Comment</ListComment>
    </ListPart>
    <ListPart>
      <ListNo>2</ListNo>
      <ListSymbol>test2</ListSymbol>
      <ListComment>test2Comment</ListComment>
    </ListPart>

</ListSection>

xXDocument xmlSource = XDocument.Load(new StringReader(strXml));
想通过xmlSource 给ListSymbol=test2的节点追加一个属性并附上值,即<ListSymbol attr="hello">test2</ListSymbol>
如何做呢,请教大家帮帮忙。谢谢

------最佳解决方案--------------------
xmlSource.Elements().Skip(1).First().Elements("ListSymbol").First().Add(new XAttribute("attr", "hello"));
------其他解决方案--------------------

//添加xml节点
    private void AddXml(string image, string title) 
    {
        XmlDocument xmlDoc = new XmlDocument();
        xmlDoc.Load(Server.MapPath("data.xml")); 
        XmlNode root = xmlDoc.SelectSingleNode("images");//查找<images>
        XmlElement xe1 = xmlDoc.CreateElement("thumb");//创建一个<thumb>节点
        xe1.SetAttribute("displayNum", "6");//设置该节点displayNum属性
        xe1.SetAttribute("separation", "5");//设置该节点separation属性
        XmlElement xesub1 = xmlDoc.CreateElement("image");
        xesub1.InnerText = image;//设置文本节点
        xe1.AppendChild(xesub1);//添加到thumb节点中
        XmlElement xesub2 = xmlDoc.CreateElement("description");
        xesub2.InnerText = title;
        xe1.AppendChild(xesub2);
        root.AppendChild(xe1);//添加到<images>节点中
        xmlDoc.Save(Server.MapPath("data.xml"));
    }