How to get xpath from an XmlNode instance

后端 未结 14 1131
难免孤独
难免孤独 2020-11-30 18:17

Could someone supply some code that would get the xpath of a System.Xml.XmlNode instance?

Thanks!

14条回答
  •  广开言路
    2020-11-30 18:51

    If you do this, you will get a Path with Names of der Nodes AND the Position, if you have Nodes with the same name like this: "/Service[1]/System[1]/Group[1]/Folder[2]/File[2]"

    public string GetXPathToNode(XmlNode node)
    {         
        if (node.NodeType == XmlNodeType.Attribute)
        {             
            // attributes have an OwnerElement, not a ParentNode; also they have             
            // to be matched by name, not found by position             
            return String.Format("{0}/@{1}", GetXPathToNode(((XmlAttribute)node).OwnerElement), node.Name);
        }
        if (node.ParentNode == null)
        {             
            // the only node with no parent is the root node, which has no path
            return "";
        }
    
        //get the index
        int iIndex = 1;
        XmlNode xnIndex = node;
        while (xnIndex.PreviousSibling != null && xnIndex.PreviousSibling.Name == xnIndex.Name)
        {
             iIndex++;
             xnIndex = xnIndex.PreviousSibling; 
        }
    
        // the path to a node is the path to its parent, plus "/node()[n]", where
        // n is its position among its siblings.         
        return String.Format("{0}/{1}[{2}]", GetXPathToNode(node.ParentNode), node.Name, iIndex);
    }
    

提交回复
热议问题