我有一個複雜的XML,這裏給出了一個簡化版本。 我試圖實現的是從XML中僅從給定節點集合 獲取數據(文本或屬性值)。許多示例僅適用於XPATH。但是我的XML結構很複雜,我想使用遞歸方法掃描節點而不是硬編碼XPATH。如何從XML中選擇多個節點以及該節點的文本或屬性值
INPUT:
<Root>
<Book>
<Content >
<Chapter id="1" startpage="1" endpage="20">
<Topic id="1">
<Title>Title1</Title>
<Content>Paragraphs</Content>
</Topic>
<Topic id="1.1">
<Title>Title1.1</Title>
<Content>Paragraphs</Content>
</Topic>
<Topic id="1.2">
<Title>Title1.2</Title>
<Content>Paragraphs</Content>
</Topic>
</Chapter>
<Chapter id="2" startpage="21" endpage="90">
<Topic id="2">
<Title>Title2</Title>
<Content>Paragraphs</Content>
</Topic>
<Topic id="2.1">
<Title>Title2.1</Title>
<Content>Paragraphs</Content>
</Topic>
<Topic id="2.1.2">
<Title>Title2.1.2</Title>
<Content>Paragraphs</Content>
</Topic>
</Chapter>
<Index>
Some more nodes here
</Index>
</Content>
</Book>
</Root>
期望的輸出:
<Root>
<Book>
<Content>
<Chapter id="1" startpage="1" endpage="20">
<Title>Title1</Title>
<Title>Title1.1</Title>
<Title>Title1.2</Title>
</Chapter>
<Chapter id="2" startpage="21" endpage="90">
<Title>Title2</Title>
<Title>Title2.1</Title>
<Title>Title2.1.2</Title>
</Chapter>
</Book>
</Root>
CURRENT XSL:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:ns="some:ns">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:strip-space elements="*"/>
<ns:WhiteList>
<name>Root</name>
<name>Book</name>
<name>Chapter</name>
<name>Title</name>
</ns:WhiteList>
<xsl:variable name="whistList" select="document('')/*/ns:WhiteList" />
<xsl:template match="node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="@*">
<xsl:if test="attribute::*[name()=$whistList/*]">
<xsl:copy/>
</xsl:if>
</xsl:template>
<xsl:template match="*">
<xsl:if test="descendant-or-self::*[name()=$whistList/*]">
<xsl:copy>
<xsl:value-of select="node()" />
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:if>
</xsl:template>
</xsl:stylesheet>
謝謝邁克爾。您的回答是準確的,並按預期工作。 – user3391883