Create XML Nodes based on XPath?

后端 未结 12 609
囚心锁ツ
囚心锁ツ 2020-11-27 15:36

Does anyone know of an existing means of creating an XML hierarchy programatically from an XPath expression?

For example if I have an XML fragment such as:

12条回答
  •  执念已碎
    2020-11-27 15:52

    If the XPath string is processed from back to front, its easier to process non rooted XPaths eg. //a/b/c... It should support Gordon's XPath syntax too although I have not tried...

    static private XmlNode makeXPath(XmlDocument doc, string xpath)
    {
        string[] partsOfXPath = xpath.Split('/');
        XmlNode node = null;
        for (int xpathPos = partsOfXPath.Length; xpathPos > 0; xpathPos--)
        {
            string subXpath = string.Join("/", partsOfXPath, 0, xpathPos);
            node = doc.SelectSingleNode(subXpath);
            if (node != null)
            {
                // append new descendants
                for (int newXpathPos = xpathPos; newXpathPos < partsOfXPath.Length; newXpathPos++)
                {
                    node = node.AppendChild(doc.CreateElement(partsOfXPath[newXpathPos]));
                }
                break;
            }
        }
    
        return node;
    }
    

提交回复
热议问题