C#XDocument将数据插入现有XML

时间:2016-10-11 15:43:18

标签: c# xml linq-to-xml

我有以下代码尝试将数据存在到现有的XMl文件中:

XDocument doc = XDocument.Load(path);
XElement root = new XElement("facilities");
root.Add(new XElement("FacilityName", "Name Data"));
root.Add(new XElement("FacilityDescription", "Description data"));
root.Add(new XElement("Type", "Type data"));
root.Add(new XElement("IPAddress", "IPAddress data"));
root.Add(new XElement("Port", "Port data"));
doc.Element("facilities").Add(root);
doc.Save(path);

生成的XML代码接近我想要的但不正确:

<Facilities>
<FacilityName>Name data</FacilityName>
<FacilityDescription>Description data</FacilityDescription>
<Type>IP</Type>
<IPAddress>127.0.0.1</IPAddress>
<Port>80</Port>
</Facilities>

<facilities>
<FacilityName>Name Data2</FacilityName>
<FacilityDescription>Description data</FacilityDescription>
<Type>Type data</Type>
<IPAddress>IPAddress data</IPAddress>
<Port>Port data</Port>
</facilities>

</facilities>

我需要将数据插入

设施 不 的设施 但是当我在我的代码中更改它时,我得到一个null异常,就像在文件中找不到...为什么?

0 个答案:

没有答案