![](/img/trans.png)
[英]to count the number of occurrence of an element with specific attribute and specific value in xml
[英]Template that matches the first occurrence of a specific element in an XML document
我有一個XML文檔,其結構類似於以下內容:
<article>
<header>
<metadata>
bunch of metadata nodes here
<abstract>
<p>this is one of the abstract's paragraphs</p>
</abstract>
</metadata>
</header>
<body>
<sec>
<title>This is title 1</title>
<p>Paragraph 1</p>
<p>paragraph 2</p>
<title>This is title 2</title>
<sec>
<title>This is title 3</title>
<p>paragraph 1 under title 3</p>
<p>paragraph 2 under title 3</p>
</body>
</article>
真正的XML肯定會比上述復雜得多,但足以說明。
我只需要對出現在<body>
元素內的第一個<p>
元素應用特定的模板。 我可以輕松地編寫一個xpath表達式,為我感興趣的節點選擇一個:
(//body//p)[1]
不幸的是,該xpath表達式不能用作XSLT中的match表達式
<xsl:template match="(//body//p)[1]">
<p_first>
<xsl:call-template name="copyElementAttributes" />
<xsl:apply-templates select="@*|node()" />
</p_first>
</xsl:template>
嘗試通過XSL引擎運行時,上面的模板將引發錯誤。 是否可以使用匹配表達式來選擇元素?
您必須使用類似
<xsl:template match="body//p[count(preceding::p) = count(ancestor::body/preceding::p)]">
即找到一個p
體內其中其他的數量內部p
元件的前面它是一樣的前方開口的數量<body>
標記。
另外
<xsl:template match="body//p[not(preceding::p[ancestor::body])]">
將尋找一個p
不具有任何前任p
是自己的后代元素body
。 該ancestor::body
,因為每一個約束是必要的body//p
由前p
是內部abstract
。 如果可能有不止一個body
元素,它將變得更加復雜,因為我們僅檢查在body
元素內的 p
s,不一定是同一 body
。
嘗試match="body//p[not(preceding::p)]"
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.