从XElement中删除属性

本文关键字:属性 删除 XElement | 更新日期: 2023-09-27 18:11:40

请考虑这个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:xsixmlns:xsd。我写了这段代码,但它不起作用:

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

我得到这个错误:

附加信息:':'字符,十六进制值0x3A,不能包含在名称中。

如何删除以上属性?

从XElement中删除属性

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

您可以尝试以下操作

//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

如果您想要使用名称空间,LINQ to XML使这非常容易:

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

这里是最后一个干净和通用的c#解决方案,用于删除所有XML名称空间:

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>