java - 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>
解决方案
这是一个相当常见的问题,快速搜索出现以下问题:
就个人而言,我认为 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 代码。
推荐阅读
- ios - 使用 Swift 将具有相同类型的字典分组到具有完整键和值的数组中
- javascript - 如何使用单击按钮在剪贴板中复制示例代码
- ggplot2 - 如何创建一个 R 闪亮的应用程序来获取 PCA 图
- c - 如何读取 C 中任意数量结构的输入,其中一个值是未定义长度的 char 数组?
- node.js - 如何通过仅拥有他们的标签来获得用户?(例如 xavia#3366)
- python - 我如何根据你的熊猫完成这个问题?
- mysql - 尽管数据库存在,但 MySql 中没有数据库选择错误
- html - 如何使用 CSS Flexbox 来弯曲多个高度/大小的盒子
- python - pandas DataFrame 的反向地理编码
- c++ - 从全局静态变量切换到静态变量会破坏代码