How to get full XPath of node?

In general, we use XPath expression to read data from XMLDocument in .Net and process the data as per the need. But not  vice-versa. So, here we will see how to get complete XPath of any XML node from available XMLDocument.

        
        private string GetCompleteXPathToNode(XmlNode node)
        {
            if (node.NodeType == XmlNodeType.Attribute)
            {
                return String.Format("{0}/@{1}", 
GetCompleteXPathToNode(((XmlAttribute)node).OwnerElement), node.Name);
            }

            if (node.ParentNode == null)
            {
                return "";
            }

            return String.Format("{0}/{1}", GetCompleteXPathToNode(node.ParentNode), node.Name);
        }

We can test this method by generating node as described in  creation of XML Node using XPath.

Comments

Popular posts from this blog

Auto Scroll in Common Controls

Convert typed library (.tlb) to .net assembly?

Disable close button on form - C#