如何修改XElement的内容?

时间:2010-04-08 22:51:37

标签: c# linq-to-xml

有一种简单的方法可以修改XElement的InnerXml吗? 我们有这个非常简单的xml

<planets>
    <earth></earth>
    <mercurio></mercurio>
</planets>

我们希望将一些来自另一个源的xml附加到地球节点中。

字符串为“<continents><america/><europa/>.....blablabla”。

我阅读了相关的问题,但他们谈到了检索XElement的innerxml,我不明白如何“修改”实际的Xelement :(

2 个答案:

答案 0 :(得分:4)

构建XML

planetsElement.Element("earth").Add(
    new XElement("continents",
        new XElement("america"),
        new XElement("europa")
    )   
);

解析并添加

planetsElement.Element("earth").Add(
   XElement.Parse("<continents><america/><europa/></continents>")
);

答案 1 :(得分:2)

使用XElement.ReplaceNodes()设置元素的内容。所以...

var doc = XDocument.Parse(xmlString);
var earth = doc.Root.Element("earth");

// to replace the nodes use
earth.ReplaceNodes(XElement.Parse("<continents><america/><europa/></continents>"));

// to add the nodes
earth.Add(XElement.Parse("<continents><america/><europa/></continents>"));