如何从XML使用C#删除所有命名空间? [英] How to remove all namespaces from XML with C#?
问题描述
我要寻找清洁,优雅和智能解决方案,从所有XML元素删除namespacees?如何将功能做到这一点的样子?
I am looking for the clean, elegant and smart solution to remove namespacees from all XML elements? How would function to do that look like?
定义接口:
public interface IXMLUtils
{
string RemoveAllNamespaces(string xmlDocument);
}
XML示例要从中删除NS:
Sample XML to remove NS from:
<?xml version="1.0" encoding="utf-16"?>
<ArrayOfInserts xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<insert>
<offer xmlns="http://schema.peters.com/doc_353/1/Types">0174587</offer>
<type2 xmlns="http://schema.peters.com/doc_353/1/Types">014717</type2>
<supplier xmlns="http://schema.peters.com/doc_353/1/Types">019172</supplier>
<id_frame xmlns="http://schema.peters.com/doc_353/1/Types" />
<type3 xmlns="http://schema.peters.com/doc_353/1/Types">
<type2 />
<main>false</main>
</type3>
<status xmlns="http://schema.peters.com/doc_353/1/Types">Some state</status>
</insert>
</ArrayOfInserts>
在我们称之为RemoveAllNamespaces(xmlWithLotOfNs),我们应该:
After we call RemoveAllNamespaces(xmlWithLotOfNs), we should get:
<?xml version="1.0" encoding="utf-16"?>
<ArrayOfInserts>
<insert>
<offer >0174587</offer>
<type2 >014717</type2>
<supplier >019172</supplier>
<id_frame />
<type3 >
<type2 />
<main>false</main>
</type3>
<status >Some state</status>
</insert>
</ArrayOfInserts>
preffered的解决方案语言是.NET 3.5 SP1 C#。
Preffered language of solution is C# on .NET 3.5 SP1.
推荐答案
嗯,这里是最后的答案。我用伟大的想法吉米(不幸的是不完整的本身)和完整的递归功能正常工作。
Well, here is the final answer. I have used great Jimmy idea (which unfortunately is not complete itself) and complete recursion function to work properly.
string RemoveAllNamespaces(string xmlDocument);
我在这里重新present最后的清洁和通用的C#解决方案去除XML命名空间:
I represent here final clean and universal C# solution for removing XML namespaces:
//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)));
}
它的工作100%,但我没有测试过很多,因此它可能不包括一些特殊情况下...但它是很好的基础开始。
It's working 100%, but I have not tested it much so it may not cover some special cases ... But it is good base to start.
这篇关于如何从XML使用C#删除所有命名空间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!