首页 > 解决方案 > How to remove XML namespace in Java

问题描述

I need to remove the namespace from an XML using Java (the project also makes use of SAX/JAXB). The example below illustrates what is needed, essentially to transform the input XML into the result XML. Any advice / working example of how this can be achieved?

Input XML:

<ns2:client xmlns:ns2="http://my-org/schemas" instance="1">

        <ns2:dob>1969-01-01T00:00:00</ns2:dob>

        <ns2:firstname>Anna</ns2:firstname>

        <ns2:married>false</ns2:married>

        <ns2:gender>Female</ns2:gender>

        <ns2:surname>Smith</ns2:surname>

        <ns2:title>Miss</ns2:title>

</ns2:client>

Result XML:

<client instance="1">

        <dob>1969-01-01T00:00:00</dob>

        <firstname>Anna</firstname>

        <married>false</married>

        <gender>Female</gender>

        <surname>Smith</surname>

        <title>Miss</title>

</client>

标签: javaxmljaxbxml-namespacessax

解决方案


这是一个相当常见的问题,快速搜索出现以下问题:

如何使用 java dom 从 xml 中删除命名空间?

从 Java 中的 XML 中删除命名空间

就个人而言,我认为 XSLT 是最明显的技术,因为这正是 XSLT 的发明目的(XML 到 XML 的转换)。我已成功使用此 XSLT 剥离命名空间(归功于https://stackoverflow.com/users/18771/tomalak):

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:template match="node()">
    <xsl:copy>
      <xsl:apply-templates select="node()|@*" />
    </xsl:copy>
  </xsl:template>

  <xsl:template match="*">
    <xsl:element name="{local-name()}">
      <xsl:apply-templates select="node()|@*" />
    </xsl:element>
  </xsl:template>

  <xsl:template match="@*">
    <xsl:attribute name="{local-name()}">
      <xsl:apply-templates select="node()|@*" />
    </xsl:attribute>
  </xsl:template>
</xsl:stylesheet>

您将找到用于在两个线程中执行该 XSLT 的 Java 代码。


推荐阅读