[英]LINQ To XML - How to read this XML?
我有一个看起来像这样的XML文件:
...
<body>
<unit id="1" name ="xxx">
<sourceFile>SomeFile.xml</sourceFile>
<targetFile/>
</unit>
<unit id="2" name ="xxx">
<sourceFile>SomeFile.xml</sourceFile>
<targetFile/>
</unit>
</body>
有人可以告诉我如何通过C#使用LINQ to XML来读取sourceFile节点的值,并更新targetFile的值,因为我不熟悉LINQ to XML?
谢谢。
像这样:
XDocument doc = XDocument.Load("file.xml");
foreach (var sourceNode in doc.Descendants("sourceFile"))
{
XElement targetNode = sourceNode.Parent.Element("targetFile");
if (targetNode != null)
{
targetNode.Value = sourceNode.Value;
}
}
或者:
XDocument doc = XDocument.Load("file.xml");
foreach (var unitNode in doc.Descendants("unit"))
{
XElement sourceNode = unitNode.Element("sourceFile");
XElement targetNode = unitNode.Element("targetFile");
if (sourceNode != null && targetNode != null)
{
targetNode.Value = sourceNode.Value;
}
}
(然后,如果您想保存回文件,请致电doc.Save
,当然,如另一个答案中所指出的。)
要更新实际文件本身,只需在加载的文档上调用Save()方法。
string path = "yourfile.xml";
XDocument doc = XDocument.Load(path);
foreach (XElement unit in doc.Descendants("unit"))
{
XElement source = unit.Element("sourceFile");
XElement target = unit.Element("targetFile");
target.Value = source.Value; // or whatever
}
doc.Save(path);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.