首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > .NET >

怎么给指定的element追加一个属性

2012-12-23 
如何给指定的element追加一个属性例如:?xml version1.0ListSectionListPartListNo1/ListNoL

如何给指定的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"));
    }

热点排行