【问题标题】:Remove attributes from XElement从 XElement 中删除属性
【发布时间】:2014-07-07 10:38:11
【问题描述】:
请考虑这个 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
【解决方案1】:
我会使用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
【解决方案3】:
如果您想使用命名空间,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>