【问题标题】:Linq to Xml : Remove namespaceLinq to Xml:删除命名空间
【发布时间】:2020-04-06 18:24:44
【问题描述】:
【问题讨论】:
标签:
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。