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

118
我正在寻找一种清晰、简洁和智能的解决方案,以删除所有XML元素中的命名空间。这个函数应该是什么样子的?

定义的接口:


定义的接口:

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

需要移除命名空间的示例 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#。


@JohnSaunders:你说得对。但在这种特殊情况下,我必须进行一些系统集成。那时这是唯一的选择。 - Peter Stegnar
@PeterStegnar 错误通常是由创建遗留格式的黑客造成的。开发人员经常滥用 XML。命名空间是第一个被抛弃的疯狂重要的功能。 - Gusdor
31个回答

-1

我认为这是最短的答案(但对于像 , 这样的构造,您将有另一个讨论),我还有正则表达式将 "<bcm:info></bcm:info>" 转换为 "<info></info>",但它没有被优化。如果有人问我,我会分享它。所以,我的解决方案是:

    public string RemoveAllNamespaces(string xmlDocument)
    {
        return Regex.Replace(xmlDocument, @"\sxmlns(\u003A\w+)?\u003D\u0022.+\u0022", " ");
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接