我想遍历下面xml中的节点并获取以下元素的值:H_Domain,H_Environment,H_Mastered。 XPathSelectElements返回IEnumerable列表,并且索引不能应用于这些XElement。任何人都知道如何在代码示例中显示每个元素的值(相对)?
private static void GetHabitation()
{
try
{
IEnumerable<XElement> list = xdoc.XPathSelectElements("//Audit/agents/agent/questions/H0/*");
foreach (XElement element in list)
{
Console.WriteLine(element["H_Domain"].Value);
Console.WriteLine(element["H_Environment"].Value);
Console.WriteLine(element["H_Mastered"].Value);
}
return haList;
}
catch (Exception)
{
throw;
}
}
XML
<?xml version="1.0" encoding="utf-8"?>
<Audit>
<agents xmlns="">
<agent>
<questions>
<H0>
<H_Domain>RAC Raccordement Basse Tension</H_Domain>
<H_Environment>CPT travaux comptage</H_Environment>
<H_Mastered>0</H_Mastered>
</H0>
<H0>
<H_Domain>IBT Intervention r�seau Basse Tension</H_Domain>
<H_Environment>TIA Travaux aux installations a�riennes</H_Environment>
<H_Mastered>0</H_Mastered>
</H0>
<H0>
<H_Domain>IBT Intervention r�seau Basse Tension</H_Domain>
<H_Environment>AEM Actes d'exploitation et man�uvre</H_Environment>
<H_Mastered>0</H_Mastered>
</H0>
</questions>
</agent>
</agents>
</Audit>
答案 0 :(得分:2)
有一个Element
方法,所以请使用
IEnumerable<XElement> list = xdoc.XPathSelectElements("//Audit/agents/agent/questions/H0");
foreach (XElement h0 in list)
{
Console.WriteLine((string)h0.Element("H_Domain"));
Console.WriteLine((string)h0.Element("H_Environment"));
Console.WriteLine((int)h0.Element("H_Mastered"));
}