[英]XPath to produce a result node-set containing the same node more than once?
我想在標題中說的是:
給定我只知道一個特定元素僅出現一次的XML,是否有可能使用單個 XPath查詢來選擇兩次包含該元素的節點集?
我知道有一個“聯合”運算符(|),但這基本上是邏輯或,對嗎? 用SQL術語來說,我正在尋找等同於“全部聯合”的東西。
例如,鑒於XML片段...
<toplevel>
<ElementIWant>
<SomeSubElement1>specific data</SomeSubElement1>
<SomeSubElement2>specific data 2</SomeSubElement2>
</ElementIWant>
</toplevel>
...是否有一個查詢,將獲得與...相等的結果集
<ElementIWant>
...identical content...
</ElementIWant>
<ElementIWant>
...identical content...
</ElementIWant>
我沒有發現任何讓我認為可以完成的事情-但這就是為什么我要問...
正如其他答案所指出的那樣,XPath無法修改XML文檔並生成新節點 。
由於"set"
的定義,任何節點只能參與一次節點"set"
。
但是,XPath 2.0為我們提供了新的序列類型 ,該序列類型允許重復項。
為了使元素在序列中出現兩次,只需使用序列連接運算符","
,如下所示:
/*/ElementYouWant, /*/ElementYouWant
像這樣簡單地將其放入XSLT2.0樣式表中:
<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:f="http://fxsl.sf.net/"
exclude-result-prefixes="f xs"
>
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:template match="/">
<t>
<xsl:sequence select=
"/*/ElementYouWant, /*/ElementYouWant"/>
</t>
</xsl:template>
</xsl:stylesheet>
並將此轉換應用於此XML文檔:
<toplevel>
<ElementYouWant>
<SomeSubElement1>specific data</SomeSubElement1>
<SomeSubElement2>specific data 2</SomeSubElement2>
</ElementYouWant>
</toplevel>
產生想要的結果:
<t>
<ElementYouWant>
<SomeSubElement1>specific data</SomeSubElement1>
<SomeSubElement2>specific data 2</SomeSubElement2>
</ElementYouWant>
<ElementYouWant>
<SomeSubElement1>specific data</SomeSubElement1>
<SomeSubElement2>specific data 2</SomeSubElement2>
</ElementYouWant>
</t>
請注意,如果使用<xsl:sequence>
指令,則不會創建<ElementYouWant>
元素的新副本-因此,在XSLT 2.0中,建議使用<xsl:sequence>
並避免使用<xsl:copy-of>
會創建(不必要的)節點副本。
XPath為您提供了節點集 ,因此根據定義,節點僅出現一次。 現在,您可以命名模板並使用相同的XPath調用它兩次。
<xsl:template match="/ElementIWant">
<xsl:call-template name="repeat"/>
<xsl:call-template name="repeat"/>
</xsl:template>
<xsl:template name="repeat">
<xsl:copy select=".">
<xsl:text>... same content ...</xsl:text>
</xsl:copy>
</xsl:template>
XPath是一種查詢XML文檔中數據的語言,而SQL UNION ALL
語法則結合了來自兩個不同查詢的結果集。
XPath本身不能用於以與現有格式不匹配的格式來顯示現有數據。 但是,您可以使用XSLT執行此轉換:
<x:stylesheet version="1.0" xmlns:x="http://www.w3.org/1999/XSL/Transform">
<x:output method="xml"/>
<x:template match="/">
<topMostLevel>
<x:apply-templates />
</topMostLevel>
</x:template>
<x:template match="toplevel">
<x:copy-of select="."/>
<x:copy-of select="."/>
</x:template>
</x:stylesheet>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.