简体   繁体   English

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

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

Given the following XML: 给定以下XML:

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

and here's my code to iterate the attributes- 这是我的代码来迭代属性-

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

Where node = "studentA", how do I get the XPath for each attribute? 在node =“ studentA”的情况下,如何获取每个属性的XPath?

EDIT: Basically what I'm trying to achieve here is to compare if two nodes are the same. 编辑:基本上我想在这里实现的是比较两个节点是否相同。 So I have to check if they have the same name, attributes, and attribute values . 因此,我必须检查它们是否具有相同的名称,属性和属性值 Therefore given a node, I need an xpath expression that that matches the conditions stated. 因此,给定一个节点,我需要一个与所述条件匹配的xpath表达式。

you can directly put it like as for all the studentA nodes- 您可以像所有StudentA节点一样直接输入-

Xpath- "//studentA" Xpath- "//studentA"

or to iterate over a specific node- Xpath- "enrollment/school/students/studentA" 或遍历特定节点-Xpath- "enrollment/school/students/studentA"

In case you want to find attribute fname 如果您要查找属性fname

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

Assuming myXml is your xmlDocument you can iterate over a particular node attributes like- 假设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