gpt4 book ai didi

xml - 如何通过 XPath 访问具有多个命名空间的 XML 中的元素?

转载 作者:行者123 更新时间:2023-12-04 16:55:01 26 4
gpt4 key购买 nike

我有一个 XML 文件,它看起来像这样:

<?xml version='1.0' encoding='UTF-8'?>
<?xml-stylesheet type="text/xsl" href="http://url/stylesheet.xsl"?>

<first xmlns="http://www.loc.gov/zing/srw/">
<element1>And</element1>
<e2>I said</e2>
<e3>
<e4>
<mods version="3.0"
xmlns:bla="http://www.w3.org/1999/xlink"
xmlns:bla2="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.loc.gov/mods/v3"
xsi:schemaLocation="http://www.loc.gov/mods/v3">
<f1>What about</f1>
<f2>Breakfast at Tiffany's</f2>
</mods>
</e4>
</e3>
</first>

另一方面,我有一个 XSL 文件可以通过 XPath 获取元素:
<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:n="http://www.loc.gov/zing/srw/"
xmlns:o="http://www.loc.gov/mods/v3">

<xsl:template match="/">
<html><head></head><body>
<xsl:value-of select="n:first/n:e2"/>
</body></html>
</xsl:template>
</xsl:stylesheet>

有了这个,我可以获取元素 e2 说我说但我有问题访问元素 f4 说蒂凡尼早餐。 XPath 是否假设元素 f4 有两个命名空间(默认命名空间 xmlns="http://www.loc.gov/zing/srw/"在根元素中首先声明 元素的命名空间mods xmlns="http://www.loc.gov/mods/v3") 或者是 mods 命名空间 xmlns="http://www.loc.gov/mods/v3"是 mods 的所有子元素的唯一命名空间元素?
并且我实际上可以更轻松地访问元素 e2 而无需在我的 xsl 文件中声明前缀吗?我刚刚开始使用 XML/XSL,所以我希望我的问题很清楚。

最佳答案

以下 XPath 表达式应该可以工作:

n:first//o:f2
mods元素在 o 中命名空间,为其他命名空间定义前缀不会改变它。它的 child 继承了命名空间。

关于xml - 如何通过 XPath 访问具有多个命名空间的 XML 中的元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12260520/

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