【发布时间】:2019-05-30 19:35:46
【问题描述】:
我想使用 XSLT 更改 XML 文件中的命名空间,仅基于 namespace-uri,而不知道这个命名空间定义了什么前缀。有可能吗?
我得到了一些解决方案,但是当我知道输入并且可以手动设置 xsl 文件时,它们仅适用于小文件。
我想要达到的目标:
输入 XML:
<?xml version="1.0" encoding="UTF-8"?>
<re:rootElement xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:re="http://something.com/root"
xmlns:ns1="http://something.com/some/schema"
xmlns:cs2="http://something.com/another/schema"
xmlns:ns3="http://something.com/different/schema"
xmlns:xsd="http://www.w3.org/2001/XMLSchema" >
<xsd:import namespace="http://something.com/another/schema" schemaLocation="/schema/location"/>
(下面有多个节点)
采用 2 个参数的 XSLT:
<xsl:param name="old_namespace" select="'http://something.com/another/schema'"/>
<xsl:param name="new_namespace" select="'http://something.com/another/schemaNEW'"/>
并输出为xml:
<re:rootElement xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:re="http://something.com/root"
xmlns:ns1="http://something.com/some/schema"
xmlns:cs2="http://something.com/another/schemaNEW"
xmlns:ns3="http://something.com/different/schema"
xmlns:xsd="http://www.w3.org/2001/XMLSchema" >
<xsd:import namespace="http://something.com/another/schemaNEW" schemaLocation="/schema/location"/>
(multiple nodes below)
【问题讨论】:
-
1.对命名空间进行参数化有多重要?不能将它们硬编码在 XSLT 样式表中吗? -- 2. 你的处理器支持 XSLT 2.0 吗?
-
1.这很重要,但现在作为一个快速解决方案,我想我会喜欢 xslt 2 中的硬编码版本。是的,我使用的是 Saxon 9
-
请注意,您的输入不是格式正确的 XML,因为前缀
re未绑定到命名空间。 -
我确实纠正了这一点。我的错。
-
在某个命名空间中很容易匹配和更改节点。对元素或属性值执行相同操作将需要使用模式感知 XSLT。或者您希望 XSLT 处理器如何知道
namespace属性包含要更改的名称空间?您知道输入 XML 的结构、可能要更改的属性吗?