简体   繁体   English

Linq to Xml:删除命名空间

[英]Linq to Xml : Remove namespace

I am retrieving an element or node from my xml doc.我正在从我的 xml 文档中检索元素或节点。 All goes well but when I retrieve the node it gets assigned the namespace of my root.一切顺利,但是当我检索节点时,它被分配了我的根的命名空间。 This I don't want.这是我不要的。 I just want the node as it was before (without namespace).我只想要以前的节点(没有命名空间)。

My element that is retrieve is eg xElement.我检索的元素是例如 xElement。 I am tried我被试过了

  1. xElement.Attributes("xmlns").Remove();
  2. xElement.Attributes("xmlns").Where(x=>x.IsNamespaceDeclaration).Remove();

None of them did the trick.他们都没有做到这一点。

I even tried this example: https://social.msdn.microsoft.com/Forums/en-US/9e6f77ad-9a7b-46c5-97ed-6ce9b5954e79/how-do-i-remove-a-namespace-from-an-xelement?forum=xmlandnetfx This left met with an element with an empty namespace xmlns=""我什至试过这个例子: https : //social.msdn.microsoft.com/Forums/en-US/9e6f77ad-9a7b-46c5-97ed-6ce9b5954e79/how-do-i-remove-a-namespace-from-an- xelement?forum=xmlandnetfx这左遇到了一个元素,它的命名空间为空xmlns=""

Please help.请帮忙。

As stated here如前所述这里

Based on interface:基于接口:

 string RemoveAllNamespaces(string xmlDocument);

I represent here final clean and universal C# solution for removing XML namespaces:我在这里代表了用于删除 XML 命名空间的最终干净和通用的 C# 解决方案:

 //Implemented based on interface, not part of algorithm public static string RemoveAllNamespaces(string xmlDocument) { XElement xmlDocumentWithoutNs = RemoveAllNamespaces(XElement.Parse(xmlDocument)); return xmlDocumentWithoutNs.ToString(); } //Core recursion function private static XElement RemoveAllNamespaces(XElement xmlDocument) { if (!xmlDocument.HasElements) { XElement xElement = new XElement(xmlDocument.Name.LocalName); xElement.Value = xmlDocument.Value; foreach (XAttribute attribute in xmlDocument.Attributes()) xElement.Add(attribute); return xElement; } return new XElement(xmlDocument.Name.LocalName, xmlDocument.Elements().Select(el => RemoveAllNamespaces(el))); }

Above solution still have two flase以上解决方案还有两个flase

  • It ignores attributes它忽略属性
  • It doesn't work with "mixed mode" elements它不适用于“混合模式”元素

Here is another solution:这是另一个解决方案:

 public static XElement RemoveAllNamespaces(XElement e)
 {
    return new XElement(e.Name.LocalName,
      (from n in e.Nodes()
        select ((n is XElement) ? RemoveAllNamespaces(n as XElement) : n)),
          (e.HasAttributes) ? 
            (from a in e.Attributes() 
               where (!a.IsNamespaceDeclaration)  
               select new XAttribute(a.Name.LocalName, a.Value)) : null);
  }          

Sample code here .示例代码在这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM