gpt4 book ai didi

xml - 将 XML 导入根节点上没有命名空间的 XSL

转载 作者:行者123 更新时间:2023-12-04 17:02:14 24 4
gpt4 key购买 nike

我正在尝试使用 XSL 将两个 XML 文件转换为 HTML。我一切正常,但我有一个问题。其中一个 XML 文件包含我从中提取的各种信息。文件中的任何地方都没有 namespace 声明,但我需要访问的节点是 namespace 前缀。我最初的修复方法是将命名空间添加到根节点,但我发现我不能这样做,因为无法修改文件。

如果我关闭命名空间,我会在 Firefox 中得到以下信息:

XML Parsing Error: prefix not bound to a namespace

命名空间应该是(但在源 XML 中不存在):
xmlns:prop="http://www.blank.com/prop" 
xmlns:item="http://www.blank.com/item"

我该如何解决这个问题?

XML:
<?xml version="1.0" encoding="UTF-8"?>
<collection>
<prop:id>123</prop:id>
<document>
<item:name>Document</item:name>
</document>
</collection>

XSL:
(元素的值都不起作用)
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="html"/>
<xsl:variable name="propsPath" select="test_Props.xml"/>
<xsl:variable name="props" select="document($propsPath)" />

<xsl:template match="/">
<html><body><div>
<xsl:value-of select="$props/collection/*[local-name() = 'id']"/>
<xsl:value-of select="$props/collection/prop:id"/>
</div></body></html>
</xsl:template>
</xsl:stylesheet>

最佳答案

编辑:这篇文章没有解决具体问题。尽管如此,我还是把它留在这里,因为它举例说明了一般问题的解决方案。

我发现的一种解决方案可以在不修改的情况下规避命名空间问题 test_Props.xml在 stub 文件中使用实体引用。

所以你的 test_Props.xml文件是这样的:

<?xml version="1.0" encoding="UTF-8"?>
<collection>
<prop:id>123</prop:id>
<document>
<item:name>Document</item:name>
</document>
</collection>

现在围绕此内容创建一个名为 test_Props_stub.xml 的 stub 文件。 :
<?xml version="1.0"?>
<!DOCTYPE doc [
<!ENTITY otherFile SYSTEM "test_Props.xml">
]>
<root xmlns:prop="http://www.blank.com/prop" xmlns:item="http://www.blank.com/item">
&otherFile;
</root>

该解决方案的灵感来自 this SO answer .
然后只需修改 document的名称及其在 XSLT 中的路径,通过添加新的根节点,您就完成了:
<xsl:variable name="propsPath" select="'test_Props_stub.xml'"/>
<xsl:variable name="props" select="document($propsPath)/root" />

其余的可以保持不变。
现在来自 root 的命名空间 stub 文件的节点应用于原始 XML 文件并且 XPath 表达式匹配。

顺便说一句,您在以下行中有一个小但令人讨厌的错误:
<xsl:variable name="propsPath" select="test_Props.xml"/>

您忘记了文件名周围的引号。

关于xml - 将 XML 导入根节点上没有命名空间的 XSL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45421857/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com