简体   繁体   中英

Using XSLT to transform XML

I have the following set XML content (basically, multiple lines with three items

  • in it) which I want to transform as follows: Instead of having:

     <line><li>1</li><li>2</li><li>3</li></line> <line><li>a</li><li>b</li><li>c</li></line> <line><li>x</li><li>y</li><li>z</li></line> 

    I would like to have:

     <line> <item1>col1<item1><li>1</li> <item2>col2<item1><li>2</li> <item3>col3<item1><li>3</li> </line> <line> <item1>col1<item1><li>a</li> <item2>col2<item1><li>b</li> <item3>col3<item1><li>c</li> </line> <line> <item1>col1<item1><li>x</li> <item2>col2<item1><li>y</li> <item3>col3<item1><li>z</li> </line> 

    Basically adding a column for ech line. Does XSLT help achieving that result? Many thanks.

  • I tried a slightly modified verion. My input XML is:

    <message>
    <line number="1"><li>1</li><li>2</li><li>3</li></line>
    <line number="2"><li>x</li><li>y</li><li>z</li>
    </line>
    <line number="3"><li>a</li><li>b</li><li>c</li>
    </line>
    </message>
    

    And my XSLT is:

    <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" encoding="utf-8" indent="no"/>
    <xsl:template match="/">
      <xsl:for-each select="/message/line">
    
    number: <xsl:value-of select="@number"/>
    position: <xsl:value-of select="position()"/>
    all items: <xsl:value-of select="."/>
    item[3]: <xsl:value-of select="li[3]"/>
    
      </xsl:for-each>
    </xsl:template>
    

    This yields:

    number: 1
    position: 1
    all items: 123
    item[3]: 3
    
    number: 2
    position: 2
    all items: xyz
    item[3]: z
    
    number: 3
    position: 3
    all items: abc
    item[3]: c
    

    My initial thoughts were to put the all items in a variable and then do the second nested for-each on that variable. But what it yields is 123 (for the first line), ommitting the

  • tags. Interestingly, when I try with the following XPath on the message:

     /message/line[1]/li 

    I obtain:

     <li>1</li> <li>2</li> <li>3</li> 

    which is the desired outcome. In my XSLT, I tried to replace "select="."" with "select="li[position()]"" but it would only return the 1st item of each line.

    Is there any explanation and what should I change to get the same outcome as my xPath?

  • 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