0

I need help in fetching the XML content between comments using XSLT.

XML:

<?xml version="1.0" encoding="ISO-8859-1"?>
<bookstore>
    <book>
        <title lang="eng">Harry Potter</title>
        <price>29.99</price>
    </book>
    <!-- start comment 1 -->
    <book>
        <title lang="it">Learning XML</title>
        <price>39.95</price>
    </book>
    <!-- end comment 1 -->

</bookstore> 

Output:

<book>
            <title lang="it">Learning XML</title>
            <price>39.95</price>
        </book>
2
  • XML comments are not the right way to do this. Is there any other distinguishing factor of the elements you are wanting to select? The lang attribute? Name? Price? Commented Jun 18, 2013 at 13:21
  • My aim here is to filter the XML part within comments and create a separate XML. For this I was trying to filter this using XSL. Commented Jun 18, 2013 at 13:25

2 Answers 2

2

You could try something like this...

XML Input

<bookstore>
    <book>
        <title lang="eng">Harry Potter</title>
        <price>29.99</price>
    </book>
    <!-- start comment 1 -->
    <book>
        <title lang="it">Learning XML</title>
        <price>39.95</price>
    </book>
    <!-- end comment 1 -->

</bookstore>

XSLT 1.0

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output indent="yes"/>
    <xsl:strip-space elements="*"/>

    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="/*">
        <xsl:apply-templates select="*[preceding-sibling::comment()[starts-with(normalize-space(.),'start')] and 
            following-sibling::comment()[starts-with(normalize-space(.),'end')]]"/>
    </xsl:template>

</xsl:stylesheet>

Output

<book>
   <title lang="it">Learning XML</title>
   <price>39.95</price>
</book>
Sign up to request clarification or add additional context in comments.

Comments

-1

Relying on comment to copy is not really good. But, I think - you have some rationale why you chose to do that. Here is my try.

<xsl:template match="/">
    <xsl:apply-templates/>
</xsl:template>

<xsl:template match="comment()">
    <xsl:if test="text()='START'">
        <!-- Set Flag for copying content <xsl:variable name="dummy" value-of="myPrefix:setFlag()"/> -->
    </xsl:if>
    <xsl:if test="text()='END'">
        <!-- Reset Flag for stop copying content -->
    </xsl:if>
</xsl:template>

Unfortunately, you can't update variables in XSLT. Maybe, you can try using your own Java class instance which can have the flag stuff which is checked by your templates to decide on copy or not.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.