2010-04-08 109 views
6

有没有简单的方法来修改XElement的InnerXml? supose我们有这个极其简单的XML如何修改XElement的内容?

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

,我们要附加一些XML是来自自带像一个字符串“<continents><america/><europa/>.....blablabla”入地节点的另一来源。

我看了相关的问题,但他们谈论检索的XElement的innerxml,我不知道如何“修改”实际的XElement :(

回答

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>") 
); 
+0

源是一个字符串,假设我们有一个节点的千串,这种形式给出是没有用的。 XmlElement具有innerXml属性,只需要赋值就可以了。如果有这样简单的方法,我的提示目标。 – mjsr 2010-04-08 23:02:58

+0

ouyea“解析和添加”是我需要的,谢谢! – mjsr 2010-04-08 23:05:27

+0

@voodoomsr - 不要忘记接受答案。 – ChaosPandion 2010-04-08 23:27:25

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>"));