1
我有這個XML文件:摺疊節點,如果沒有其他因素是其間
<?xml version="1.0" encoding="iso-8859-1"?>
<doclist>
<text attribute="a">This is a <tag1>sentence</tag1> <tag1>with</tag1> a few
<tag1>words</tag1>.</text>
<-- many more text nodes with none, one or several '<tag1>' in it -->
</doclist>
,我希望得到這樣的結果:
<?xml version="1.0" encoding="iso-8859-1"?>
<doclist>
<text attribute="a">This is a <tag1>sentence with</tag1> a few <tag1>words</tag1>.
</text>
<-- many more text nodes with none, one or several '<tag1>'s in it -->
</doclist>
我試圖用正則表達式做:
<xsl:template match="text">
<text>
<xsl:apply-templates select="@*"/> <!-- templ. to copy attributes of text -->
<xsl:analyze-string select="."
regex="<tag1>(.+)<tag1><tag1>(.+)</tag1>">
<!-- also tried . instead of < -->
<xsl:matching-substring>
<xsl:for-each select=".">
<tag1>
<xsl:value-of-select="regex-group(1)">
<xsl:text> <xsl:text>
<xsl:value-of-select="regex-group(2)">
</tag1>
</xsl:matching-substring>
<xsl:non-matching-substring>
<xsl:for each select=".">
<xsl:value-of select="."/>
</xsl:for-each>
</xsl:non-matching-substring>
</xsl:analyze-string>
</text>
</xsl:template>
但我的輸出如下所示:
<?xml version="1.0" encoding="iso-8859-1"?>
<doclist>
<text attribute="a>This is a sentencewitha few words.
</text>
<-- many more text nodes with none, one or several '<tag1>'s in it -->
</doclist>
我的猜測,什麼情況是,比賽的arent發現,因爲沒有<tag1>
出現S的結果 - 但我不明白爲什麼只有標籤surounded的話失去了空格... 我該如何正確崩潰<tag1>
是直接的鄰居嗎?
thx,我添加了匹配tag1和使用group-adjacent(不知道他們)的模板。輸出看起來像預期的結果。我想知道,爲什麼「或self :: text()」是需要的。我看了一下o'reillys xslt書,並且用「boolean(self :: tag1)」來試用它,但是它沒有摺疊元素。兩者有什麼區別?另外,我很好奇你爲什麼用代替元素。這是一種風格習慣嗎? –
Beehgr
在XPath數據模型中,XSLT在輸入序列'句子 和 上操作導致在元素節點上構成的節點序列,具有單個空白字符和第二個元素節點的文本節點。我們希望將它們三個組合在一起,這就是爲什麼我使用'xsl:for-each-group select =「node()」group-adjacent =「self :: tag1或self :: text()[not ('normalize-space())]'。 –
至於使用'xsl:copy',如果你有'match ='text'''''''''允許您使用相同的模板處理多個元素,即如果您有其他元素需要相同的處理,則可以使用' ... xsl:for-each-group> xsl:template>'。 –