如何通过XPath访问具有多个名称空间的XML元素? [英] How can i access elements in XML with several namespaces via XPath?
问题描述
我有一个看起来像这样的XML文件:
I've got an XML file which looks somehow like this:
<?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来获取元素:
On the other hand I have an XSL-file to grab the elements via 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元素? 我实际上可以在没有在xsl文件中声明前缀的情况下更轻松地访问e2元素吗?我刚刚开始使用XML/XSL,所以希望我的问题很清楚.
With this I can fetch the element e2 saying I said but I have problems to access element f4 saying Breakfast at Tiffany's . Does XPath assume that the element f4 has two namespaces (the default namespace xmlns="http://www.loc.gov/zing/srw/" declared in the root element first and the namespace of the element mods xmlns="http://www.loc.gov/mods/v3") or is the mods namespace xmlns="http://www.loc.gov/mods/v3" the only namespace for all childelements of the mods element? And can I actually access the element e2 easier without the declaration of prefixes in my xsl-file? I am just starting to use XML/XSL, so I hope my question is clear.
推荐答案
以下XPath表达式应该起作用:
The following XPath expression should work:
n:first//o:f2
mods
元素位于o
命名空间中,为其他命名空间定义前缀不会更改它.它的子级继承名称空间.
The mods
element is in the o
namespace, defining prefixes for other namespaces does not change it. Its children inherit the namespace.
这篇关于如何通过XPath访问具有多个名称空间的XML元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!