繁体   English   中英

在现有文档中填充XML元素

[英]Populate XML elements in existing document

我在文档中有这串XML元素

<dmc><avee><modelic></modelic><sdc></sdc><chapnum></chapnum><section></section>
<subsect></subsect><subject></subject><discode></discode><discodev></discodev>
<incode></incode><incodev></incodev><itemloc></itemloc></avee></dmc>

现在,我需要做的是使用Linq用用户输入的变量填充这些元素。 我目前有:

XDocument doc = XDocument.Load(sgmlReader);
doc.Element("modelic").Add(MI);
doc.Element("sdc").Add(sd);
doc.Element("chapnum").Add(sys);
doc.Element("section").Add(subsys);
doc.Element("subsect").Add(subsubsys);
doc.Element("subject").Add(unit);
doc.Element("discode").Add(dc);
doc.Element("discodev").Add(dcv);
doc.Element("incode").Add(infcode);
doc.Element("incodev").Add(infCV);
doc.Element("itemloc").Add(loc);

(是的,我正在使用sgmlReader,但是这在我的程序中的其他区域工作正常)我显然缺少一些基本的东西,因为它给了我一个NullReferenceException was unhandled - Object reference not set to an instance of an objectNullReferenceException was unhandled - Object reference not set to an instance of an object

有什么想法/建议吗?

这应该工作:

        var avee = dmc.Root.Element("avee");
        avee.Element("modelic").Value = MI;
        avee.Element("sdc").Value = sd;

只需对其余的每个元素( chapnumsection ...)重复最后一行。

问题在于,首先必须检索根元素( dmc ),然后avee ,然后才能为avee子元素设置值。

Element()方法仅匹配容器的直接子代。

您可以将Descendants()链接First()中

doc.Descendants("modelic").First().Add(MI);

或导航到要修改的元素的直接父级:

doc.Root.Element("avee").Element("modelic").Add(MI);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM