gpt4 book ai didi

c# - LINQ 到 XML : How to get all elements by value

转载 作者:行者123 更新时间:2023-11-30 20:52:47 26 4
gpt4 key购买 nike

我正在尝试从 xml 文档中获取所有具有给定值“John”的元素。

这可以通过 LINQ to XML 实现吗?

我想要实现的是用“Wayne”替换所有“John”值。我知道这可以使用 xslt 轻松完成,但我需要通过代码来完成。

我的 XML:

<Root>
<Parents>
<Parent>
<Name>John</Name>
<Age>18</Age>
</Parent>
<Parent>
<Name>John</Name>
<Age>25</Age>
</Parent>
<Parent>
<Name>Peter</Name>
<Age>31</Age>
</Parent>
</Parents>
</Root>

我试过这个:

XmlDocument doc = new XmlDocument();
doc.Load(@"C:/Temp/test.xml");

var elements = doc.Elements().Where(w => w.Value == "John");
foreach (var element in elements)
{
element.Value = "Wayne";
}

最佳答案

您可以使用 System.Xml.Linq.XDocument .它更易于使用。

XDocument doc = XDocument.Load(your file path);

var elements = doc.Descendants("Name").Where(i => i.Value == "John");

foreach (var element in elements)
{
element.Value = "Wayne";
}

doc.Save(your save file path);

这是输出:

<?xml version="1.0" encoding="utf-8"?>
<Root>
<Parents>
<Parent>
<Name>Wayne</Name>
<Age>18</Age>
</Parent>
<Parent>
<Name>Wayne</Name>
<Age>25</Age>
</Parent>
<Parent>
<Name>Peter</Name>
<Age>31</Age>
</Parent>
</Parents>
</Root>

关于c# - LINQ 到 XML : How to get all elements by value,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20568740/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com