2010-06-03 71 views
4

XPath可以獲得節點的所有子節點的連接視圖嗎?我正在尋找類似於JQuery .html()方法的東西。如何連接XPath中節點的所有子節點的內容?

舉例來說,如果我有下面的XML:

<h3 class="title"> 
    <span class="content">this</span> 
    <span class="content"> is</span> 
    <span class="content"> some</span> 
    <span class="content"> text</span> 
</h3> 

我想上一個XPath查詢「H3 [@類=‘標題’]」這會給我「這是一些文本」。

這是一個真正的問題,但如果更多的上下文/背景有幫助,這裏是:我正在使用XPath,並且我使用this post來幫助我編寫一些複雜的XSL。我的源XML看起來像這樣。

<h3 class="title">Title</h3> 
<p> 
    <span class="content">Some</span> 
    <span class="content"> text</span> 
    <span class="content"> for</span> 
    <span class="content"> this</span> 
    <span class="content"> section</span> 
</p> 
<p> 
    <span class="content">Another</span> 
    <span class="content"> paragraph</span> 
</p> 
<h3 class="title"> 
    <span class="content">Title</span> 
    <span class="content"> 2</span> 
    <span class="content"> is</span> 
    <span class="content"> complex</span> 
</h3> 
<p> 
    <span class="content">Here</span> 
    <span class="content"> is</span> 
    <span class="content"> some</span> 
    <span class="content"> text</span> 
</p> 

我的輸出XML考慮每個<h3>以及所有<p>標籤,直到下一個<h3>。我寫的XSL如下:

<xsl:template match="h3[@class='title']"> 
... 
    <xsl:apply-templates select="following-sibling::p[ 
     generate-id(preceding-sibling::h3[1][@class='title'][text()=current()/text()]) 
     = 
     generate-id(current()) 
    ]"/> 
... 
</xsl:template> 

的問題是,我使用text()方法來識別是相同的3H公司。在上面的例子中,「Title 2 is complex」標題的text()方法返回空白。我的想法是使用像JQuery的.html這樣的方法,將返回我「標題2是複雜的」。

更新:這可能有助於澄清。轉換之後,上述所需的輸出會是這個樣子:

<section> 
    <title>Title</title> 
    <p> 
     <content>Some</content> 
     <content> text</content> 
     <content> for</content> 
     <content> this</content> 
     <content> section</content> 
    </p> 
    <p> 
     <content>Another</content> 
     <content> paragraph</content> 
    </p> 
</section> 
<section> 
    <title> 
     <content>Title</content> 
     <content> 2</content> 
     <content> is</content> 
     <content> complex</content> 
    </title> 
    <p> 
     <content>Here</content> 
     <content> is</content> 
     <content> some</content> 
     <content> text</content> 
    </p> 
</section> 
+0

已添加完整樣式表以響應添加完整的所需輸出。 – 2010-06-09 13:43:38

+0

這是一個方便的工具(對於任何其他人有類似的任務)http://codebeautify.org/Xpath-Tester – Rimian 2015-09-18 11:21:46

回答

5
h3[@class='title']/span[@class='content']/text() 

喜歡這個?

h3[@class='title']/descendant::*/text() 

或者這個?

+0

是的,這似乎有幫助,但它扭轉了我的問題。現在,它將拾取「標題2是複雜的」中的文本,但它不會拾取沒有跨度的「標題」中的文本。 是否有XPath可以同時使用? 最糟糕的是,目前只有跨度,但實際上可能有任何標籤。我真的希望有一個解決方案能夠將文本從任何標籤中提取出來。 – Brian 2010-06-04 14:17:02

+0

新的解決方案:這將拾取所有後代的內容(遞歸!) – nuqqsa 2010-06-04 14:25:11

+0

啊!看起來解決方法是使用//運算符代替跨度(它將從當前節點中選擇符合選擇的文檔中的節點,而不管它們在哪裏)的建議。這似乎工作。看起來好像我不能在註釋中放入代碼片段,但select子句的h3部分現在看起來像這樣:h3 [1] [@ class ='title'] [// text()= current() //文本()])。 – Brian 2010-06-04 14:27:11

相關問題