xslt - 如何将 xml 的一部分转换为没有命名空间的新 xml?
问题描述
我在将部分 xml 转换为没有命名空间的新 xml 时遇到了麻烦。输入xml是:
<?xml version="1.0" encoding="ISO-8859-1" standalone="no"?>
<node1 xmlns="http://a.com">
<ServiceData>
<b:test xmlns:b="http://b.com">
<b:somtag>
</b:somtag>
</b:test>
</ServiceData>
</node1>
我想要的是:
<a>
<c>
<ServiceData>
<b:test xmlns:b="http://b.com">
<b:somtag>
</b:somtag>
</b:test>
</ServiceData>
</c>
</a>
我想要的格式是没有 ServiceData 的命名空间。任何帮助表示赞赏,谢谢。
补充,我尝试使用这个 xsl,但我无法删除 "xmlns="http://a.com""
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:test="http://a.com" exclude-result-prefixes="test">
<xsl:output method="xml" encoding="UTF-8" omit-xml-declaration="yes" />
<xsl:template match="/">
<a><c><ServiceData><xsl:copy-of select="//test:ServiceData/*"/></ServiceData></c></a>
</xsl:template>
</xsl:stylesheet>
我得到的结果是:
<a>
<c>
<ServiceData>
<b:test xmlns:b="http://b.com" xmlns="http://a.com">
<b:somtag>
</b:somtag>
</b:test>
</ServiceData>
</c>
</a>
解决方案
怎么样:
XSLT 2.0
<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xpath-default-namespace="http://a.com">
<xsl:output method="xml" encoding="UTF-8" indent="yes" />
<xsl:template match="/node1">
<a>
<c>
<ServiceData>
<xsl:copy-of select="ServiceData/*" copy-namespaces="no" />
</ServiceData>
</c>
</a>
</xsl:template>
</xsl:stylesheet>
添加:
我假设您可以使用 XSLT 2.0 处理器,因为您的样式表显示version="2.0"
. 如果那不是真的,那么你不能使用xsl:copy-of
; 相反,您必须使用其原始名称和命名空间重构元素:
XSLT 1.0
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:test="http://a.com"
exclude-result-prefixes="test">
<xsl:output method="xml" version="1.0" encoding="utf-8" indent="yes"/>
<xsl:template match="/test:node1">
<a>
<c>
<ServiceData>
<xsl:apply-templates select="test:ServiceData/*"/>
</ServiceData>
</c>
</a>
</xsl:template>
<xsl:template match="*">
<xsl:element name="{name()}" namespace="{namespace-uri()}">
<xsl:apply-templates/>
</xsl:element>
</xsl:template>
</xsl:stylesheet>
笔记:
多余的命名空间声明不应对接收应用程序产生任何影响。此处收到的结果在语义上与您在问题中显示的结果相同。
推荐阅读
- python - Python pandas:我们可以避免在 groupby/apply 这种情况下应用吗?
- python - 使用 gunicorn 运行 myapp 会出现错误“没有名为 myapp 的模块”
- c++ - 尝试只插入单词的第一个字母,而不是整个单词
- c++ - 为什么我不能在三元表达式中使用 return 但我可以在常规 if-else 语句中使用?
- c# - 监控桌面 C# 应用程序上的使用指标
- json - 匹配选定的行以传递数据
- java - Retrofit 2 - RxJava:无法为 retrofit2.Call 调用无参数构造函数
- python - 如何在不打开计算机的情况下保持 discord python bot 运行?
- javascript - 从文本文件中读取 URL,然后将文件下载为 exe。Javascript
- nginx - 找不到 Dokku 子域