【问题标题】:Linq to Xml : Remove namespaceLinq to Xml:删除命名空间
【发布时间】:2020-04-06 18:24:44
【问题描述】:

我正在从我的 xml 文档中检索元素或节点。一切顺利,但是当我检索节点时,它被分配了我的根的命名空间。这是我不想要的。我只想要以前的节点(没有命名空间)。

我的检索元素是例如x元素。 我试过了

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

他们都没有成功。

我什至试过这个例子: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=""

请帮忙。

【问题讨论】:

    标签: c# .net xml linq linq-to-xml


    【解决方案1】:

    如上所述here

    基于接口:

    string RemoveAllNamespaces(string xmlDocument);
    

    我在这里代表用于删除的最终干净和通用的 C# 解决方案 XML 命名空间:

    //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)));
        }
    

    上面的解决方案还有两个flase

    • 它忽略属性
    • 它不适用于“混合模式”元素

    这是另一个解决方案:

     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);
      }          
    

    示例代码here

    【讨论】: