简体   繁体   中英

How do I get different values from the same variable in XML using XSL

XML:

<message code="100" description="checkSnr">
  <string name="id"/>
  <string name="serialNr"/>
</message>

XSL:

<xsl:template match="/">
  <xsl:for-each select="machine/events"> 
    <xsl:text>;</xsl:text>
    <xsl:value-of select="message/@code"/>
    <xsl:text>;</xsl:text>
    <xsl:value-of select="message/string/@name"  />
    <xsl:text>;</xsl:text>
    <xsl:value-of select="message/string/@name"  />
  </xsl:for-each>
</xsl:template>

So here's my Problem. My XSL-File is supposed to detect the value "id" and the value "serialNr", but my Output is "id" x2. I know it is only Logical but how can I actually Change my XSL so it gives me both of the values? (by the way, in the XML there are parts, where the variable "string Name" is used like 4 times) I thought of rewriting the XML with a Loop so that the Name variables get renamed into name1, name2, name3 and so on, but I can't figure out how to do that. I use Java as a converter if you can think of any Solutions in Java. My Output Format is .CSV if that matters.

(any other tips on improving the XSL are appreciated aswell)

Thanks!

It is strange that you have 2 empty string tags.

I suppose, your XML should have the following shape:

<message code="100" description="checkSnr">
  <string name="id">1234</string>
  <string name="serialNr">5678</string>
</message>

Then you shoud read both string tags using name attribute with particular value as a predicate :

<xsl:template match="/">
  <xsl:for-each select="machine/events"> 
    <xsl:text>;</xsl:text>
    <xsl:value-of select="message/@code"/>
    <xsl:text>;</xsl:text>
    <xsl:value-of select="message/string[@name='id']"  />
    <xsl:text>;</xsl:text>
    <xsl:value-of select="message/string[@name='serialNr']"  />
  </xsl:for-each>
</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