小编典典

如何使用C#从XML中删除所有名称空间?

c#

我是否在寻找一种干净,优雅,智能的解决方案,以从所有XML元素中删除名称空间?看起来如何起作用?

定义的接口:

public interface IXMLUtils
{
        string RemoveAllNamespaces(string xmlDocument);
}

从以下示例中删除NS的示例XML:

<?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)之后,我们应该获得:

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

解决方案的首选语言是.NET 3.5 SP1上的C#。


阅读 306

收藏
2020-05-19

共1个答案

小编典典

好吧,这是最终答案。我使用了很好的Jimmy想法(不幸的是,它本身并没有完成),并且使用了完整的递归功能才能正常工作。

基于接口:

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

它正在100%正常工作,但是我没有对其进行太多测试,因此它可能无法涵盖某些特殊情况……但这是一个很好的起点。

2020-05-19