c#:获取xml元素的属性xpath

时间:2015-02-11 04:57:24

标签: c# xml xpath xml-parsing

鉴于以下XML:

<enrollment>
    <school>
        <students>
            <studentA fname="John" lname="Doe" age="23" />
            <studentB fname="Mary" lname="Johnson" age="22" /> 
        </students>  
    </school>  
</enrollment>

这里是我的代码来迭代属性 -

foreach(XmlAttribute attr in node.Attributes)
{
    //--get the XPath for each attribute 
}

其中node =&#34; studentA&#34;,如何获取每个属性的XPath?

修改 基本上我在这里尝试实现的是比较两个节点是否相同。所以我必须检查他们是否具有相同的名称,属性和属性值。因此,给定一个节点,我需要一个与所述条件相匹配的xpath表达式。

2 个答案:

答案 0 :(得分:2)

你可以直接把它放在所有studentA节点上 -

Xpath- "//studentA"

或迭代特定节点 - Xpath- "enrollment/school/students/studentA"

如果您想查找属性fname

Xpath- "enrollment/school/students/studentA[@fname]"

假设myXml是你的xmlDocument 您可以迭代特定节点属性,如 -

        System.Xml.XmlNode xn =  myXml.SelectSingleNode("enrollment/school/students/studentA");
        foreach (System.Xml.XmlAttribute attrib in xn.Attributes)
        {
            // find attribute name using attrib.Name
            string sAttribName = attrib.Name;
            if (sAttribName == "fname")
            {
                //Check your codes here
            }               
        }

答案 1 :(得分:0)

You can use enrollment/school/students/studentA/@fname

@attribute用于属性选择。