简体   繁体   English

LINQ to XML:如何按值获取所有元素

[英]LINQ to XML: How to get all elements by value

I'm trying to get all elements with a given value, "John", from an xml document. 我正在尝试从xml文档中获取具有给定值“ John”的所有元素。

Is this possible with LINQ to XML? LINQ to XML有可能吗?

What I want to achieve is to replace all "John" values with "Wayne". 我要实现的是用“ Wayne”替换所有“ John”值。 I know this can easily be done with xslt, but I need to do this by code. 我知道可以使用xslt轻松完成此操作,但是我需要通过代码来完成此操作。

My XML: 我的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>

I have tried this: 我已经试过了:

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

You may use System.Xml.Linq.XDocument . 您可以使用System.Xml.Linq.XDocument It's more easy to work with. 使用起来更容易。

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

Here is the output: 这是输出:

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

Here is an approach that will get all elements with the value John, regardless of what element (although only at the same level; you'd have to modify it to look at different levels too; you could use the Descendants approach described previously): 这是一种将获得所有值均为John的元素的方法,而不管是哪个元素(尽管仅在同一级别;您也必须对其进行修改以查看不同的级别;您可以使用前面描述的Descendants方法):

  XDocument doc = XDocument.Load(@"C:\temp\test.xml");

    var ns = doc.Root.GetDefaultNamespace();
  var elements = doc.Element(ns + "Root").Element(ns + "Parents").Elements(ns + "Parent").Elements().Where(w => w.Value == "John");
  foreach (var element in elements)
  {
    element.Value = "Wayne";
  }

    var stream = new FileStream(@"C:\temp\test.xml", FileMode.Create);

  doc.Save(stream);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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