从 XElement 中删除属性

问题描述 投票:0回答:4

请考虑这个 XElement:

<MySerializeClass xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <F1>1</F1>
    <F2>2</F2>
    <F3>nima</F3>
</MySerializeClass>

我想从上面的 XML 中删除

xmlns:xsi
xmlns:xsd
。 我写了这段代码,但它不起作用:

 XAttribute attr = xml.Attribute("xmlns:xsi");
 attr.Remove();

我收到此错误:

附加信息:名称中不能包含“:”字符(十六进制值 0x3A)。

如何删除以上属性?

c# xml c#-4.0 linq-to-xml
4个回答
9
投票

我会用

xml.Attributes().Where(a => a.IsNamespaceDeclaration).Remove()
。或者使用
xml.Attribute(XNamespace.Xmlns + "xsi").Remove()


2
投票

您可以尝试以下方法

//here I suppose that I'm loading your Xelement from a file :)
 var xml = XElement.Load("tst.xml"); 
 xml.RemoveAttributes();

来自MSDN

Removes the attributes of this XElement


0
投票

如果您想使用命名空间,LINQ to XML 使这变得非常简单:

xml.Attribute(XNamespace.Xmlns + "xsi").Remove();

这里是用于删除所有 XML 命名空间的最终干净且通用的 C# 解决方案:

public static string RemoveAllNamespaces(string xmlDocument)
{
    XElement xmlDocumentWithoutNs = RemoveAllNamespaces(XDocument.Load(xmlDocument).Root);

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

输出

 <MySerializeClass>
  <F1>1</F1> 
  <F2>2</F2> 
  <F3>nima</F3> 
 </MySerializeClass>

0
投票

更清洁的方式。

  1. 声明扩展方法:

     public static void RemoveXmlAttributes(this XElement xDocument)
     {
         xDocument.RemoveAttributes();
         foreach (XElement xmlChild in xDocument.Elements())
         {
             xmlChild.RemoveXmlAttributes();
         }
     }
    
  2. 然后调用它:

         XElement xml = XElement.Load(completionXml);
         xml.RemoveXmlAttributes();
    

可以对 XmlElement(而不是 XElement)执行相同的操作

© www.soinside.com 2019 - 2024. All rights reserved.