使用C#和LINQ to XML在XML文件中选择属性值

时间:2014-02-12 17:30:08

标签: c# xml linq-to-xml

在此XML文件中,我希望获得用ID属性

编写的所有 ID
<?xml version="1.0"?>
<root>
  <head>
    <datemaj>20140206-15-04-00</datemaj>
  </head>
  <PressReleases>
    <PressRelease id="545" version="1">
      <Name>Convert number to string</Name>
      <Date>20/05/1985</Date>
      <Input>1</Input>
      <Output>One</Output>
    </PressRelease>
    <PressRelease id="544" version="1">
      <Name>Find succeeding characters</Name>
      <Date>19/05/1985</Date>
      <Input>abc</Input>
      <Output>def</Output>
    </PressRelease>
    <PressRelease id="543" version="1">
      <Name>Convert multiple numbers to strings</Name>
      <Date>17/05/1985</Date>
      <Input>123</Input>
      <Output>One Two Three</Output>
    </PressRelease>
    <PressRelease id="542" version="1">
      <Name>Find correlated key</Name>
      <Date>02/05/1985</Date>
      <Input>a1</Input>
      <Output>b1</Output>
    </PressRelease>
    <PressRelease id="541" version="1">
      <Name>Count characters</Name>
      <Date>04/02/1985</Date>
      <Input>This is a test</Input>
      <Output>14</Output>
    </PressRelease>
    <PressRelease id="540" version="1">
      <Name>Another Test</Name>
      <Date>09/01/1985</Date>
      <Input>Test Input</Input>
      <Output>10</Output>
    </PressRelease>
  </PressReleases>
</root>

我尝试了这段代码,但是它没有返回任何内容

        XDocument xdoc = XDocument.Load(@"C:\Users\ARNAUD\Documents\local\temp.xml");
        List<int> IDsInDistantXML = xdoc.Root.Elements("PressRelease")
                            .Select(pr => (int)pr.Attribute("id"))
                            .ToList();

PS:正确找到了XML文件。

2 个答案:

答案 0 :(得分:2)

尝试Descendants

 List<int> IDsInDistantXML = xdoc.Descendants("PressRelease")
                        .Select(pr => (int)pr.Attribute("id"))
                        .ToList();

问题是你的PressRelease元素不是你root元素的直接子元素。所以什么都没有,你可以使用:

xdoc.Root.Element("PressReleases").Elements("PressRelease")

答案 1 :(得分:2)

PressRelease个节点是PressReleases的子节点,它是root的子节点

在这种情况下,您需要更改如下:

List<int> IDsInDistantXML = xdoc.Root.Element("PressReleases")
                                     .Elements("PressRelease")
                                     .Select(pr => (int)pr.Attribute("id"))
                                     .ToList();