Hi, I am trying to extract attribute value from a xml using xslt. The snippets are below.
XSlt to extract the data from attributes . Used when loop to extract attribute data.
<?xml version="1.0" encoding="iso-8859-1"?>
<!-- Edited by XMLSpy® -->
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>
<body>
<h2>My CD Collection</h2>
<table border="1">
<tr bgcolor="#9acd32">
<th>Title</th>
<th>Artist</th>
</tr>
<tr>
<xsl:choose>
<xsl:when test="//catalog/cd/title/artist/country/item/@id='mod1'">
<td>asdfg</td>
<xsl:choose>
<xsl:when test="//catalog/cd/title/artist/country/item/item/@id='up1'">
<td>
<xsl:value-of select="//catalog/cd/title/artist/country/item/item/@value" />
</td>
</xsl:when>
<xsl:otherwise/>
</xsl:choose>
</xsl:when>
<xsl:otherwise/>
</xsl:choose>
</tr>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
XML data to be parsed.
<?xml version="1.0" encoding="utf-8"?>
<!-- Edited by XMLSpy -->
<catalog>
<cd>
<title>
<artist>
<country>
<item type="layer" id="mod" title="Mod" result="pass">
<item type="measure" id="up" title="Up" value="10" unit="dBm" />
<item type="measure" id="down" title="Down" value="9.6" unit="dBm" />
</item>
<item type="layer" id="mod1" title="Mod1" result="pass">
<item type="measure" id="up1" title="Up" value="100" unit="dBm" />
<item type="measure" id="down1" title="Down" value="9.60" unit="dBm" />
</item>
</country>
</artist>
</title>
</cd>
</catalog>
Expected Output and Actual Output Below:
Expected output:
My CD Collection
Title | Artist
asdfg | 100
Actual Output:
My CD Collection
Title | Artist
asdfg | 10
Would be really thankful for a solution. Thanks in advance.
Basically, the logic in your XSLT is saying:
value
attribute of the first item's item in the document To accomplish what you are trying to do, you can do this:
<?xml version="1.0" encoding="iso-8859-1"?>
<!-- Edited by XMLSpy® -->
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>
<body>
<h2>My CD Collection</h2>
<table border="1">
<tr bgcolor="#9acd32">
<th>Title</th>
<th>Artist</th>
</tr>
<tr>
<xsl:variable name="mod1"
select="//catalog/cd/title/artist/country/item[@id = 'mod1']" />
<xsl:if test="$mod1">
<td>asdfg</td>
<xsl:variable name="up1" select="$mod1/item[@id = 'up1']" />
<xsl:if test="$up1">
<td>
<xsl:value-of select="$up1/@value" />
</td>
</xsl:if>
</xsl:if>
</tr>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
As XSLT goes, this isn't very representative of what well-written XSLT looks like, but I am putting it here as an example because I assume that this is not your ultimate goal and that you are trying this as a step toward your final goal.
For the next step, I suggest opening up a new question.
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.