Jul 10, 2012

How to create XML Node using XPath?

1 comment
In general, we use XPath expression to read data from XMLDocument in .Net and process the data as per the need. Recently i got an requirement like creation of XML Node from XPath expression.

Using the following simple code, i am able to manage creation of node from XPath.

private XmlNode GenerateNodeFromXPath(string xpath)
        {
            XmlDocument doc = new XmlDocument();
            return GenerateNodeFromXPath(doc, doc as XmlNode, xpath);
        }

        private XmlNode GenerateNodeFromXPath(XmlDocument doc, XmlNode parent, string xpath)
        {
            // grab the next node name in the xpath; or return parent if empty
            string[] partsOfXPath = xpath.Trim('/').Split('/');

            if (partsOfXPath.Length == 0)
                return parent;

            string nextNodeInXPath = partsOfXPath[0];
            if (string.IsNullOrEmpty(nextNodeInXPath))
                return parent;


            // get or create the node from the name
            XmlNode node = parent.SelectSingleNode(nextNodeInXPath);
            if (node == null)
            {
                if (nextNodeInXPath.StartsWith("@"))
                {
                    XmlAttribute anode = doc.CreateAttribute(nextNodeInXPath.Substring(1));
                    node = parent.Attributes.Append(anode);
                }
                else
                    node = parent.AppendChild(doc.CreateElement(nextNodeInXPath));
            }

            // rejoin the remainder of the array as an xpath expression and recurse
            string rest = String.Join("/", partsOfXPath, 1, partsOfXPath.Length - 1);
            return GenerateNodeFromXPath(doc, node, rest);
        }

It is Done. You can try with different XPath expressions.

If you feel this is helpful or you like it, Please share this using share buttons available on page.

1 comment :