2014-02-12 107 views
2

在這種XML文件中的XML文件屬性值,我想獲得的所有標識寫在ID屬性選擇使用C#和LINQ to XML

<?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文件正確找到。

+1

'/根/ PressReleases/PressRelease' –

+0

我很好奇,是(我的編輯前)它實際*縮進/格式化的原*'XML'內容?我發現它可讀性差和容易出錯 –

回答

3

嘗試Descendants

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

的問題是你PressRelease元素是沒有直接子你root element.So你什麼也得不到,而是可以使用:

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

後裔的作品,非常感謝您的幫助 – Slrg

3

PressRelease節點的子節點這是子節點root

In這種情況下,您需要更改如下:

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