我是XML的新手。如何读取后代的成员/子节点?
<ho>
<pro NAME="J1">
<type>C1</type>
<ID>2</ID>
<sta ID="A">Junk1</sta>
<sta ID="B">Junk2</sta>
</pro>
<pro NAME="J2">
<type>C2</type>
<ID>3</ID>
<sta ID="A">Junk3</sta>
<sta ID="B">Junk4</sta>
</pro>
</ho>
XDocument doc = XDocument.Load(file);
foreach (XElement element in doc.Descendants("pro"))
{
string pro_attribute = element.Attribute("NAME").Value;
//I can get pro_attribute J2
if ( pro_attribute =="J2")
{
//how to get getJunk 3 and 4 without having to
//read/loop through Junk1 and 2
foreach (XElement element1 in doc.Descendants("sta"))
{
//I could do this, but it will start with Junk 1.
//I want to start with Junk3 instead
}
}
}
最佳答案
带着一点Linq
var result = doc.Descendants("pro")
.Select(p => new
{
Name = p.Attribute("NAME").Value,
Type = (string)p.Element("type"),
ID = (string)p.Element("ID"),
Stas = p.Descendants("sta")
.Select(sta => new
{
ID = sta.Attribute("ID").Value,
Value = (string)sta
}).ToList()
})
.ToList();
您也可以使用
XPath
:var result = doc.XPathSelectElements("//pro[@NAME='J2']")
.......
.......
关于c# - 如何读取后代的成员/子节点?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20429507/