我在一个文档中有这个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 object。
有什么想法/建议吗?
发布于 2013-03-06 21:30:05
Element()方法只匹配容器的直接子对象。
您可以将Descendants()链接到First()中
doc.Descendants("modelic").First().Add(MI);或导航到要修改的元素的直接父项:
doc.Root.Element("avee").Element("modelic").Add(MI);发布于 2013-03-06 21:29:36
这应该是可行的:
var avee = dmc.Root.Element("avee");
avee.Element("modelic").Value = MI;
avee.Element("sdc").Value = sd;只需对剩余的每个元素(chapnum、section...)重复最后一行。
问题是,首先必须检索根元素(dmc),然后是avee,然后才能为avee的子元素设置值。
https://stackoverflow.com/questions/15248511
复制相似问题