简体   繁体   English

LINQ To XML-如何读取此XML?

[英]LINQ To XML - How to read this XML?

I've got an XML file that looks like this: 我有一个看起来像这样的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>

Can someone show me how I would use LINQ to XML via C# to read the value of the sourceFile node, and update the value of targetFile as I'm not familiar with LINQ to XML? 有人可以告诉我如何通过C#使用LINQ to XML来读取sourceFile节点的值,并更新targetFile的值,因为我不熟悉LINQ to XML?

Thanks. 谢谢。

Something like this: 像这样:

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;
    }
}

Alternatively: 或者:

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;
    }
}

(And call doc.Save afterwards if you want to save back to a file, of course, as pointed out in another answer.) (然后,如果您想保存回文件,请致电doc.Save ,当然,如另一个答案中所指出的。)

To update the actual file itself, you just need to call the Save() method on the loaded document. 要更新实际文件本身,只需在加载的文档上调用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.

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