开发者

LINQ To XML - How to read this XML?

开发者 https://www.devze.com 2023-02-17 23:58 出处:网络
I\'ve got an XML file that looks like this: ... <body> <unit id=\"1\" name =\"xxx\"> <sourceFile>SomeFile.xml</sourceFile>

I've got an XML file that looks like this:

...
<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?

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.)


To update the actual file itself, you just need to call the Save() method on the loaded document.

    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);
0

精彩评论

暂无评论...
验证码 换一张
取 消