如何使用 .NET XML API 删除 xmlns 属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/76424/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 09:53:31  来源:igfitidea点击:

How to remove xmlns attribute with .NET XML API

.netxmlapixml-namespaces

提问by axk

XmlElement.Attributes.Remove* methods are working fine for arbitrary attributes resulting in the removed attributes being removed from XmlDocument.OuterXml property. Xmlns attribute however is different. Here is an example:

XmlElement.Attributes.Remove* 方法适用于任意属性,导致从 XmlDocument.OuterXml 属性中删除已删除的属性。然而 Xmlns 属性是不同的。下面是一个例子:

XmlDocument doc = new XmlDocument();
doc.InnerXml = @"<Element1 attr1=""value1"" xmlns=""http://mynamespace.com/"" attr2=""value2""/>";
doc.DocumentElement.Attributes.RemoveNamedItem("attr2");
Console.WriteLine("xmlns attr before removal={0}", doc.DocumentElement.Attributes["xmlns"]);
doc.DocumentElement.Attributes.RemoveNamedItem("xmlns");
Console.WriteLine("xmlns attr after removal={0}", doc.DocumentElement.Attributes["xmlns"]);

The resulting output is

结果输出是

xmlns attr before removal=System.Xml.XmlAttribute
xmlns attr after removal=
<Element1 attr1="value1" xmlns="http://mynamespace.com/" />

The attribute seems to be removed from the Attributes collection, but it is not removed from XmlDocument.OuterXml. I guess it is because of the special meaning of this attribute.

该属性似乎已从 Attributes 集合中删除,但并未从 XmlDocument.OuterXml 中删除。我猜是因为这个属性的特殊含义。

The question is how to remove the xmlns attribute using .NET XML API. Obviously I can just remove the attribute from a String representation of this, but I wonder if it is possible to do the same thing using the API.

问题是如何使用 .NET XML API 删除 xmlns 属性。显然,我可以从它的 String 表示中删除该属性,但我想知道是否可以使用 API 来做同样的事情。

@Edit: I'm talking about .NET 2.0.

@Edit:我说的是 .NET 2.0。

采纳答案by GregK

.NET DOM API doesn't support modifying element's namespace which is what you are essentially trying to do. So, in order to solve your problem you have to construct a new document one way or another. You can use the same .NET DOM API and create a new element without specifying its namespace. Alternatively, you can create an XSLT stylesheet that transforms your original "namespaced" document to a new one in which the elements will be not namespace-qualified.

.NET DOM API 不支持修改元素的命名空间,而这正是您想要做的。因此,为了解决您的问题,您必须以某种方式构建一个新文档。您可以使用相同的 .NET DOM API 并创建一个新元素,而无需指定其命名空间。或者,您可以创建一个 XSLT 样式表,将您的原始“命名空间”文档转换为一个新文档,其中的元素将不符合命名空间限定。

回答by ALI SHAH

I saw the various options in this thread and come to solve my own solution for removing xmlns attributes in xml. This is working properly and has no issues:

我在这个线程中看到了各种选项,并来解决我自己的用于删除 xml 中的 xmlns 属性的解决方案。这工作正常,没有问题:

'Remove the Equifax / Transunian / Experian root node attribute that have xmlns and load xml without xmlns attributes.
If objXMLDom.DocumentElement.NamespaceURI <> String.Empty Then
  objXMLDom.LoadXml(objXMLDom.OuterXml.Replace(objXMLDom.DocumentElement.NamespaceURI, ""))
  objXMLDom.DocumentElement.RemoveAllAttributes()
  ResponseXML = objXMLDom.OuterXml
End If

There is no need to do anything else to remove xmlns from xml.

无需执行任何其他操作即可从 xml 中删除 xmlns。

回答by Matt Harris

Many thanks to Ali Shah, this thread solved my problem perfectly! here's a C# conversion:

非常感谢 Ali Shah,这个线程完美地解决了我的问题!这是一个 C# 转换:

var dom = new XmlDocument();
        dom.Load("C:/ExampleFITrade.xml));
        var loaded = new XDocument();
        if (dom.DocumentElement != null)
            if( dom.DocumentElement.NamespaceURI != String.Empty)
            {
                dom.LoadXml(dom.OuterXml.Replace(dom.DocumentElement.NamespaceURI, ""));
                dom.DocumentElement.RemoveAllAttributes();
                loaded = XDocument.Parse(dom.OuterXml);
            }

回答by pcmaniak

public static string RemoveXmlns(string xml)
{
    //Prepare a reader
    StringReader stringReader = new StringReader(xml);
    XmlTextReader xmlReader = new XmlTextReader(stringReader);
    xmlReader.Namespaces = false; //A trick to handle special xmlns attributes as regular
    //Build DOM
    XmlDocument xmlDocument = new XmlDocument();
    xmlDocument.Load(xmlReader);
    //Do the job
    xmlDocument.DocumentElement.RemoveAttribute("xmlns"); 
    //Prepare a writer
    StringWriter stringWriter = new StringWriter();
    XmlTextWriter xmlWriter = new XmlTextWriter(stringWriter);
    //Optional: Make an output nice ;)
    xmlWriter.Formatting = Formatting.Indented;
    xmlWriter.IndentChar = ' ';
    xmlWriter.Indentation = 2;
    //Build output
    xmlDocument.Save(xmlWriter);
    return stringWriter.ToString();
}

回答by Vin

Wasn't this supposed to remove namespaces?

这不是应该删除命名空间吗?

XmlNamespaceManager mgr = new XmlNamespaceManager("xmlnametable");
mgr.RemoveNamespace("prefix", "uri");

But anyway on a tangent here, the XElement, XDocument and XNameSpaceclasses from System.Xml.Linq namespace (.Net 3.0) are a better lot than the old XmlDocument model. Give it a go. I am addicted.

但无论如何,System.Xml.Linq 命名空间(.Net 3.0)中的 XElement、XDocument 和XNameSpace 类比旧的 XmlDocument 模型要好很多。搏一搏。我上瘾了。

回答by Vin

We can convert the xml to a string, remove the xmlns from that string, and then create another XmlDocument using this string, which will not have the namespace.

我们可以将 xml 转换为字符串,从该字符串中删除 xmlns,然后使用此字符串创建另一个 XmlDocument,该字符串将不具有命名空间。

回答by Vin

Yes, because its an ELEMENT name, you can't explicitly remove it. Using XmlTextWriter's WriteStartElement and WirteStartAttribute, and replacing the attribute with empty spaces will likely to get the job done.

是的,因为它是一个 ELEMENT 名称,您不能明确删除它。使用 XmlTextWriter 的 WriteStartElement 和 WirteStartAttribute,并用空格替换该属性可能会完成工作。

I'm checking it out now. will update.

我现在正在检查。会更新。

回答by MatthieuGD

Maybe trough the XmlNamespaceManager ? http://msdn.microsoft.com/en-us/library/system.xml.xmlnamespacemanager.removenamespace.aspxbut it's just a guess.

也许通过 XmlNamespaceManager ?http://msdn.microsoft.com/en-us/library/system.xml.xmlnamespacemanager.removenamespace.aspx但这只是一个猜测。

回答by Rodrigo Serzedello

here is my solution on vb.net guys!

这是我在 vb.net 上的解决方案!

   Dim pathXmlTransformado As String = "C:\Fisconet4\process79094100019215387-1387_transformado.xml"
    Dim nfeXML As New XmlDocument
    Dim loaded As New XDocument

    nfeXML.Load(pathXmlTransformado)

    nfeXML.LoadXml(nfeXML.OuterXml.Replace(nfeXML.DocumentElement.NamespaceURI, ""))
    nfeXML.DocumentElement.RemoveAllAttributes()

    Dim dhCont As XmlNode = nfeXML.CreateElement("dhCont")
    Dim xJust As XmlNode = nfeXML.CreateElement("xJust")
    dhCont.InnerXml = 123
    xJust.InnerXml = 123777

    nfeXML.GetElementsByTagName("ide")(0).AppendChild(dhCont)
    nfeXML.GetElementsByTagName("ide")(0).AppendChild(xJust)

    nfeXML.Save("C:\Fisconet4\process79094100019215387-1\teste.xml")