输出带有特定属性的XML

本文关键字:XML 属性 输出带 | 更新日期: 2023-09-27 18:13:25

很抱歉我是一个完全的新手,但也许s/o可以为我指出正确的方向!我从网上得到了代码,我试图使它工作,但它不会:(XML是这样的:

<bla>
    <blub>
        <this that="one">test one</this>
        <this that="two">test two</this>
        <this that="three">test three</this>
    </blub>
</bla>


我想要显示"this",其中"that"=="two",正如你可能知道的;)但它只适用于第一个(1),而不适用于"2"或"3"。

为什么不继续到第2和第3元素?谢谢你的建议!

  XElement tata = XElement.Load(@"''somewhere'test.xml");
  var tutu = from titi in tata.Elements("blub")
             where (string)titi.Element("this").Attribute("that") == "two"
             select titi.Element("this");
  foreach (XElement soso in tutu)
  {
           Console.WriteLine(soso.Value);
  }

输出带有特定属性的XML

你的问题在这里:

where (string)titi.Element("this").Attribute("that") == "two"

特别是Element(),其中获得第一个(按文档顺序)具有指定XName的子元素,在您的情况下恰好是test one

相反,使用XDocument而不是XElement,并查看文档中的所有元素:

XDocument tata = XDocument.Load(@"''somewhere'test.xml");
var tutu = from titi in tata.Descendants("this")
           where titi.Attribute("that").Value == "two"
           select titi;