繁体   English   中英

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

[英]c#: get the attribute's xpath for an xml element

给定以下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 =“ studentA”的情况下,如何获取每个属性的XPath?

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

您可以像所有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
            }               
        }
You can use enrollment/school/students/studentA/@fname

@attribute用于属性选择。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM