[英]How To Add new XElement Child when Parent Element is null
I have an XML document with an Element that is null: 我有一个XML文档,其Element为null:
<Home>
<Screen01 Code="BD"/>
</Home>
I want to add new child elements to the Screen01 element: 我想向Screen01元素添加新的子元素:
<Home>
<Screen01 Code="BD">
<Child1>N</Child1>
<Child2>2</Child2>
</Screen01>
</Home>
The following code gives me an error "Object reference not set to an instance of an object." 以下代码给我一个错误“对象引用未设置为对象的实例”。
Edit-I changed the code to use the way someone suggested. 编辑-我更改了代码以使用某人建议的方式。
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"));
}
How can I add new elements to Screen01 when it is null? 当它为null时,如何向Screen01添加新元素?
LINQ to XML and its XElement data type to the rescue. LINQ to XML及其XElement数据类型得以抢救。
c#
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"));
}
Output XML: 输出XML:
<Home>
<Screen01 Code="BD">
<Child1>N</Child1>
<Child2>2</Child2>
</Screen01>
</Home>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.