ImportNode creates empty xmlns attribute

≡放荡痞女 提交于 2019-12-21 08:54:42

问题


Regrading this code:

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

    if (oldNode.ParentNode != null)
    {
        oldNode.ParentNode.ReplaceChild(tmpNewNode, oldNode);
        return true;
    }

tmpNewNode is created with empty xmlns attribute (xmlns=""). Any suggestion how can I avoid it?

10x


回答1:


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.




回答2:


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.




回答3:


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)




回答4:


Try:

oldNode.InnerXml = tmpNewNode.InnerXml



回答5:


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=\"\"", ""));



回答6:


add default namespace to your xdoc



来源:https://stackoverflow.com/questions/4336367/importnode-creates-empty-xmlns-attribute

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!