Jul 10, 2012

How to get full XPath of node?

1 comment
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.

1 comment :