代码之家  ›  专栏  ›  技术社区  ›  mjsr

如何修改Xelement的内容?

  •  6
  • mjsr  · 技术社区  · 16 年前

    有没有一个简单的方法来修改Xelement的innerXML? supose我们有这个非常简单的XML

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

    我们希望附加一些来自另一个源的XML,这些源类似于字符串。” <continents><america/><europa/>.....blablabla “进入地球节点。

    我读过相关的问题,但他们谈论的是检索Xelement的innerXML,我不理解如何“修改”实际Xelement:。(

    2 回复  |  直到 16 年前
        1
  •  4
  •   ChaosPandion    16 年前

    构建XML

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

    解析和添加

    planetsElement.Element("earth").Add(
       XElement.Parse("<continents><america/><europa/></continents>")
    );
    
        2
  •  2
  •   AxelEckenberger    16 年前

    使用 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>"));
    
    推荐文章