首页 > 解决方案 > 当父元素为空时如何添加新的 XElement 子元素

问题描述

我有一个元素为空的 XML 文档:

<Home>
    <Screen01 Code="BD"/>
</Home>

我想向 Screen01 元素添加新的子元素:

<Home>
    <Screen01 Code="BD">
        <Child1>N</Child1>
        <Child2>2</Child2>
    </Screen01>            
</Home>

以下代码给了我一个错误“对象引用未设置为对象的实例。”

编辑-我更改了代码以使用某人建议的方式。

 private void CreateAddRRNodes(string xmlAfterAttribsAdded)
 {
            XElement xDoc = XElement.Parse(xmlAfterAttribsAdded);
            xDoc.Element("Screen01").Add(new XElement("Child1", "N"));
            xDoc.Element("Screen01").Add(new XElement("Child2", "1"));
  }

当 Screen01 为空时,如何向 Screen01 添加新元素?

标签: c#xml

解决方案


LINQ to XML 和它的 XElement 数据类型来拯救。

C#

void Main()
{
    XElement xml = XElement.Parse(@"<Home>
                                <Screen01 Code='BD'/>
                            </Home>");

    xml.Element("Screen01").Add(new XElement("Child1", "N"));
    xml.Element("Screen01").Add(new XElement("Child2", "2"));
}

输出 XML:

<Home>
  <Screen01 Code="BD">
    <Child1>N</Child1>
    <Child2>2</Child2>
  </Screen01>
</Home>

推荐阅读