ImportNode creates empty xmlns attribute

后端 未结 6 1793
误落风尘
误落风尘 2021-02-20 08:34

Regrading this code:

   var tmpNewNode = xdoc.ImportNode(newNode, true);

    if (oldNode.ParentNode != null)
    {
        oldNode.ParentNode.ReplaceChild(tmpNe         


        
相关标签:
6条回答
  • 2021-02-20 08:36

    add default namespace to your xdoc

    0 讨论(0)
  • 2021-02-20 08:39

    I got the sames problem when I created an XmlElement like here

    XmlElement xmlElement = myXmlDocument.CreateElement("MyElemenent");
    myXmlDocument.AppendChild(xmlElement);
    

    after this I got the attribute xmlns="" after saving.

    If I use the namespace of the document I could suppress this xmlns attribute.

    XmlElement xmlElement = myXmlDocument.CreateElement("MyElemenent",myXmlDocument.DocumentElement.NamespaceURI);
    myXmlDocument.AppendChild(xmlElement);
    

    Without the empty xmlns="" my SelectNodes didn't work anymore because the namespace needs to be specified. Solution for this is here (using-xpath-with-default-namespace)

    0 讨论(0)
  • 2021-02-20 08:51

    Along the lines of what MarkXA said:

    What's probably happening here is that newNode comes from a document with no namespace declared, but oldNode is in a document with a namespace. In this situation, the node takes its blank namespace over to the new document and it shows up explicitly.

    You could manipulate the String for the purpose of the comparison but the nodes in your DOM would not be namespace qualified correctly which could cause you problems later if you tried to use it.

    The correct solution would be to build newNode with the proper namespace qualification in the first place. By propery namespace qualification, I mean the namespaces used in the importing DOM.

    0 讨论(0)
  • 2021-02-20 08:55

    Finally i solved this opening xml file and replace all ocurrences of xmlns "" with a empty string.

    Maybe its not elegant solution but its simple and works fine.

    //remove void xmlns
    File.WriteAllText(filename, Regex.Replace(File.ReadAllText(filename), "xmlns=\"\"", ""));
    
    0 讨论(0)
  • 2021-02-20 08:59

    Try:

    oldNode.InnerXml = tmpNewNode.InnerXml
    
    0 讨论(0)
  • 2021-02-20 09:00

    What's probably happening here is that newNode comes from a document with no namespace declared, but oldNode is in a document with a namespace. In this situation, the node takes its blank namespace over to the new document and it shows up explicitly. To be honest, if it's only a problem for a string comparison, it won't hurt to just remove all instances of xmlns="" from the XML string before you work with it.

    0 讨论(0)
提交回复
热议问题