如何读取后代的成员/子节点?

时间:2013-12-06 17:01:56

标签: c# xml

我是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
        }
    }
}

2 个答案:

答案 0 :(得分:4)

带一点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']")
                .......
                .......

答案 1 :(得分:1)

更改

    foreach(XElement element1 in doc.Descendents("sta")) 

    foreach(XElement staElement in element.Elements("sta"))

因为元素对象现在指向j2,你可以使用方法Elements来获取你感兴趣的元素列表并迭代它。