0

我的 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);
4

1 回答 1

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();
于 2013-06-03T11:34:48.757 回答