[英]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
文件,我想获得全部写在了标识 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>
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. PS:正确找到XML
文件。
Try Descendants
尝试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: 问题是您的PressRelease
元素不是root
元素的直接子元素,因此您一无所获,而是可以使用:
xdoc.Root.Element("PressReleases").Elements("PressRelease")
PressRelease
nodes are child nodes of PressReleases
which is child node of root
PressRelease
节点的子节点PressReleases
这是子节点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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.