1

Similar Build XML by XPATH expressions question can be found in Java End:

As we know, there are many tools that can generate XML from XSD file, and I already have below NOT-SO-ROBUST code to build XML by XPATH expressions.

However, it can not handle complex scenarios. Combining the information from XSD, ideally, we should be able to handle any scenarios, and build XML by XPATH expressions.

I'm wondering, whether someone already did that?

It is not duplicate question to this topic. Below code already can handle simple node creation. I need emphasize that, there are many different xml styles, if we just focus on xml itself, without XSD information, the output is unpredictable, it could work, or just got stuck because of exception.

            XmlNode node=xmlDoc.SelectSingleNode(xpath,nsmgr);

            if(node==null){
                node=makeXPath(xmlDoc,nsmgr, xpath);
            }

            if(node is XmlAttribute){

                XmlAttribute formId = (XmlAttribute) node;
                if (formId != null)
                {
                    formId.Value = value1; // Set to new value.
                }
            }
            else if (node is XmlElement){
                XmlElement formData = (XmlElement)node;
                if (formData != null)
                {
                    formData.InnerText=value1; // Set to new value.
                }
            }

....... ....... ....... ....... ....... .......

        static private XmlNode makeXPath(XmlDocument doc,XmlNamespaceManager nsmgr, string xpath)
        {
            return makeXPath(doc, nsmgr,doc as XmlNode, xpath);
        }

        static private XmlNode makeXPath(XmlDocument doc, XmlNamespaceManager nsmgr,XmlNode parent, string xpath)
        {
            // grab the next node name in the xpath; or return parent if empty
            string[] partsOfXPath = xpath.Trim('/').Split('/');
            string nextNodeInXPath = partsOfXPath.First();
            if (string.IsNullOrEmpty(nextNodeInXPath))
                return parent;

            XmlNode node = parent.SelectSingleNode(nextNodeInXPath,nsmgr);
            if (node == null){
                string nextNodeInXPath_new=new Regex(@"\[\d+\]").Replace(nextNodeInXPath,"");
                node = parent.AppendChild(doc.CreateElement(nextNodeInXPath_new));
            }

            string rest = String.Join("/", partsOfXPath.Skip(1).ToArray());
            return makeXPath(doc, nsmgr,node, rest);
        }
Fang Dong
  • 33
  • 1
  • 7
  • Possible duplicate of [Create XML Nodes based on XPath?](https://stackoverflow.com/questions/508390/create-xml-nodes-based-on-xpath) – Tom Blodget Nov 03 '17 at 23:02
  • Did you try the msdn tool : https://learn.microsoft.com/en-us/dotnet/standard/serialization/xml-schema-definition-tool-xsd-exe – jdweng Nov 04 '17 at 01:00
  • Not a duplicate question, I added the reason above. – Fang Dong Nov 06 '17 at 19:27

0 Answers0