2012-09-04 116 views
1

我有,看起來在某種程度上像這樣的XML文件:如何通過XPath使用多個名稱空間訪問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元素的所有childelements的唯一命名空間? 而且我可以更容易地訪問元素e2,而無需在我的xsl文件中聲明前綴?我剛開始使用XML/XSL,所以我希望我的問題很明確。

回答

1

以下XPath表達式應該工作:

n:first//o:f2 

mods元件處於o命名空間中,限定了用於其他命名空間不改變它的前綴。它的子節點繼承這個命名空間。

+0

謝謝,那已經幫了我。因此,連接到下一個父節點的一個名稱空間爲其中的所有子元素定義名稱空間。 – JJJ

+1

@JJJ:除非它們使用前綴或其他xmlns覆蓋它。 – choroba

1

只是爲了擴大choroba的答案 - 因爲mod重置默認xmlns,則需要相應地調整你的命名空間別名,即全面走的是:

<xsl:value-of select="/n:first/n:e3/n:e4/o:mods/o:f2/text()"/> 

如果您在XSLT忽略的命名空間,您可以使用local-name()檢查不論其命名空間的節點(未在這種情況下推薦的,因爲你可以看到,這會變得非常詳細)

<xsl:value-of select="/*[local-name()='first']/*[local-name()='e3'] 
         /*[local-name()='e4']/*[local-name()='mods'] 
         /*[local-name()='f2']/text()"/> 

您可以刪除別名從輸出文件(html)中添加exclude-result-prefixes="n o"到您的xsl:stylesheet

我建議不要養成使用'//'的習慣,因爲可能導致解析器在大型文檔上進行不必要的處理。

相關問題