我的XML看起来像这样:
<Settings>
<Display_Settings>
<Screen>
<Name Name="Screen" />
<ScreenTag Tag="Screen Tag" />
<LocalPosition X="12" Y="81" Z="28" />
<Width Width="54" />
<Height Height="912" />
</Screen>
<Screen>
<Name Name="Screen" />
<ScreenTag Tag="Screen Tag" />
<LocalPosition X="32" Y="21" Z="28" />
<Width Width="54" />
<Height Height="912" />
</Screen>
</Display_Settings>
</Settings>
如何从两个具有相同名称的不同节点读取两个不同的Local Position X属性值?
修改的
抱歉,忘记添加我从一个屏幕节点读取单个本地位置属性值的代码:
var xdoc = XDocument.Load("C:\\Test.xml");
var screenPosition = xdoc.Descendants("Screen").First().Element("LocalPosition");
int screenX1 = int.Parse(screenPosition1.Attribute("X").Value);
答案 0 :(得分:2)
XPath看起来像这样:
/Settings/Display_Settings/Screen/LocalPosition/@X
您可以使用以下在线工具:http://www.freeformatter.com/xpath-tester.html#ad-output来测试您的XPath。 另外,这里有一个很好的教程:http://www.w3schools.com/xpath/
随着问题的更新,代码:
var xdoc = XDocument.Load(@"C:\darbai_test\so_Test.xml");
var screenPosition = xdoc
.Descendants("Screen")
.Descendants("LocalPosition")
.Attributes("X");
foreach (var xAttribute in screenPosition)
{
Console.WriteLine(xAttribute.Value);
}
Console.ReadKey();