【问题标题】:How do I modify the contents of an XElement?如何修改 XElement 的内容?
【发布时间】:2010-04-09 07:14:24
【问题描述】:

有没有一种简单的方法来修改 XElement 的 InnerXml? 假设我们有这个非常简单的 xml

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

我们希望将一些来自另一个来源的 xml 附加到地球节点中,例如字符串“&lt;continents&gt;&lt;america/&gt;&lt;europa/&gt;.....blablabla”。

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

【问题讨论】:

    标签: c# linq-to-xml


    【解决方案1】:

    构建 XML

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

    解析和添加

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

    【讨论】:

    • 源是一个字符串,假设我们有一个包含数千个节点的字符串,这种方法是没有用的。 XmlElement 具有 innerXml 属性,只需要一个赋值。如果有这样的简单方法,我的建议目标。
    • 好吧混沌我不知道
    【解决方案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>"));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-05-15
      • 1970-01-01
      • 1970-01-01
      • 2011-06-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多