简体   繁体   中英

Transform xml data using xslt

I am having trouble transforming a XML file with data not included in specific tags, using XSLT. Here an example of what I am trying to do :

XML input :

<test>
    <h1>some text here</h1>
    <h4 class="orange">Other text here</h4> 
    TEXT I WANT TO HAVE ACCESS TO
    <personalTag/>
</test>

XSLT file :

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:fn="http://www.w3.org/2005/xpath-functions">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:template match="/">
    <p> h1 text : <xsl:value-of select="test/h1"/> </p>
    <p> h4 text : <xsl:value-of select="test/h4"/> </p>
    <p> direct text : <xsl:value-of select="test"/> </p>
</xsl:template>

The output I want to have :

<?xml version="1.0" encoding="UTF-8"?>
<p> h1 text : some text here </p>
<p> h4 text : other text here </p>
<p> direct text : TEXT I WANT TO HAVE ACCESS TO </p>

But when I do this transformation, I have this result XML :

<?xml version="1.0" encoding="UTF-8"?>
<p> h1 text : some text here </p>
<p> h4 text : other text here </p>
<p> direct text :some text here other text here TEXT I WANT TO HAVE ACCESS TO </p>

Anyone has an idea on how to do this ? Thanks in advance.

PS: The title might not be clear enough, but I didn't know how to explain the problem I'm facing.

You're looking for the text() function, which returns only the text directly associated to the specified node:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                              xmlns:xs="http://www.w3.org/2001/XMLSchema" 
                              xmlns:fn="http://www.w3.org/2005/xpath-functions">
  <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
  <xsl:template match="/">
    <p> h1 text       : <xsl:value-of select="test/h1"    /> </p>
    <p> h4 text       : <xsl:value-of select="test/h4"    /> </p>
    <p> all test text : <xsl:value-of select="test"       /> </p>
    <p> direct text   : <xsl:value-of select="test/text()"/> </p>
  </xsl:template>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM