Adding a prefix to an xml node

前端 未结 2 724
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-03 22:33

Current File Format


Value1
Value2
Value3



        
相关标签:
2条回答
  • 2020-12-03 23:08

    If you are trying to add namespace to the elements after loading the xml document then it is not possible.

    From MSDN:

    You cannot add, modify, or delete an XML namespace definition in an instance of an XML document after the document has been loaded into the XML Document Object Model (XMLDOM) parser. The XML nodes that are used to represent data in the XML document are created when the document is loaded into the XMLDOM parser. These nodes are permanently bound to their XML namespace attributes when they are created. Therefore, the empty XML namespace declaration (xmlns = "") is appended to the child nodes of these nodes to preserve the default XML namespace attribute of these nodes.

    However you can load the input, read each element and write it to another document (or in-memory) which has the namespace set. Below is the code that parses the string xml, creates a new xml element along with namespace prefix and namespace.

                String xmlWithoutNamespace =
                    @"<Folio><Node1>Value1</Node1><Node2>Value2</Node2><Node3>Value3</Node3></Folio>";
                String prefix ="vs";
                String testNamespace = "http://www.testnamespace/vs/";
                XmlDocument xmlDocument = new XmlDocument();
    
                XElement folio = XElement.Parse(xmlWithoutNamespace);
                XmlElement folioNode = xmlDocument.CreateElement(prefix, folio.Name.LocalName, testNamespace);
    
                var nodes = from node in folio.Elements()
                            select node;
    
                foreach (XElement item in nodes)
                {
                    var node = xmlDocument.CreateElement(prefix, item.Name.ToString(), testNamespace);
                    node.InnerText = item.Value;
                    folioNode.AppendChild(node);
                }
    
                xmlDocument.AppendChild(folioNode);
    

    xmlDocument now contains the xml with each node prefixed with vs.

    0 讨论(0)
  • 2020-12-03 23:14
     private static void SetPrefix(string prefix, XmlNode node)
        {
            node.Prefix = prefix;
            foreach (XmlNode n in node.ChildNodes)
            {
                //if (node.ParentNode != null)
                //{
                if (n.Name.Contains("QualifyingProperties"))
                {
                    break;
                }
                //}
                SetPrefix(prefix, n);
            }
        }
    
    0 讨论(0)
提交回复
热议问题