来自特定元素节点的XML抓取属性

时间:2013-12-13 17:35:07

标签: c# xml

如果myVariable = "Element"然后给我该元素内的属性。

XML:

<Products>
<Equity>
    <servers>
       <serverEQ>server1</serverEQ>
       <serverEQ>server2</serverEQ>
       <serverEQ>server3</serverEQ>
    </servers>
<sitesE>
      <sitesEQ sitePathEQ="\Logs\W3SVC1"><nameEQ>SystemAdmin Site</nameEQ></sitesEQ>
      <sitesEQ sitePathEQ="\Logs\W3SVC3"><nameEQ>Direct Access Site</nameEQ></sitesEQ>
      <sitesEQ sitePathEQ="\Logs\W3SVC4"><nameEQ>Redirect Site</nameEQ></sitesEQ>
      <sitesEQ sitePathEQ="\Logs\W3SVC5"><nameEQ>Download Site</nameEQ></sitesEQ>
</sitesE>
</Equity>
.
.
.
</Products>

例如:如果myVariable = "Direct Access Site"给我\Logs\W3SVC3作为我的输出。

1 个答案:

答案 0 :(得分:3)

不清楚你想要什么,但这可能会有所帮助:

var myVariable = "Direct Access Site";
XDocument doc = XDocument.Load(your file);
var result = doc.Descendants("sitesEQ")
               .Where(i => i.Element("nameEQ").Value == myVariable )
               .Select(i => i.Attribute("sitePathEQ").Value);

foreach (string item in result)
{
    Console.WriteLine(item);
}