【发布时间】:2012-03-08 20:02:06
【问题描述】:
我正在编写一个函数来更新我的 XML,但遇到了一些问题。我希望我可以直接将旧的 XElement 设置为更新的 XElement,但这在 foreach 循环中不起作用(尽管应该只是一个查询结果)。我打算对每个字段进行硬编码,但后来决定使用循环。但是,当它到达该部分及其子元素时,它会将其全部作为单个元素读取并弄乱文件
var myDevice = from c in appDataXml.Descendants("device")
where (string)c.Element("name") == App.CurrentDeviceName
&& (string)c.Element("ip") == App.CurrentIp
select c;
if (myDevice.Any())
{
foreach (XElement device in myDevice)
{
//device.Element("customname").Value = updatedDevice.Element("customname").Value;
for (int a = 0; a < device.Elements().Count(); a++)
{
string field = device.Elements().ElementAt(a).Name.ToString();
device.Element(field).Value = updatedDevice.Element(field).Value;
}
}
}
示例 XML
<Devices>
<device>
<name>blah</name>
<customname>custom</customname>
<ip>192.168.1.100</ip>
<port>1000</port>
<sources>
<source>
<code>00</code>
<name>blah2</name>
<hidden>False</hidden>
</source>
<source>
...etc
</sources>
</device>
【问题讨论】:
标签: c# .net xml linq linq-to-xml