简体   繁体   中英

Select attributes value in XML file using C# and LINQ to XML

In this XML file, i would like to get all the IDs written in the ID attributes

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

I tried this block of code , but it returns nothing :

        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: the XML file is correctly found.

Try Descendants

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

The problem is your PressRelease element's are not direct child of your root element.So you get nothing, instead you can use:

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

PressRelease nodes are child nodes of PressReleases which is child node of root

In this case you will need to change as follows:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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