c# - 当父元素为空时如何添加新的 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 添加新元素?
解决方案
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>
推荐阅读
- maven - 创建 Jenkins Pipeline 时出现 Maven 问题
- sql - 通过比较子详细信息查找公共数据集
- flutter - 在颤振网页上重新加载页面时“未找到”
- excel - 如何为工作簿中的每个 Listobject 表使用 .DataBodyRange.Delete
- c# - 带有 if 语句的 LINQ to SQL
- sparql - 如何按原始顺序选择OWLList的所有项目?
- r - 使用 REBUS(或普通正则表达式)在 R 中提取棘手的文本
- amazon-web-services - S3 创建存储桶强制标签策略不起作用
- floating-point - 如何判断一个数字是否完全可以表示为 32 位 IEEE 浮点数?
- javascript - 想要删除这些高图图表标签前面的项目符号