Mircsicz
Mircsicz

Reputation: 75

trying to read XML value's with xsltproc

I'm want to read from but can't figure out how...

Here's the file:

<MBusData>

    <SlaveInformation>
        <Id>5000619</Id>
        <Manufacturer>SBC</Manufacturer>
        <Version>19</Version>
        <Medium>Electricity</Medium>
        <AccessNumber>254</AccessNumber>
        <Status>00</Status>
        <Signature>0000</Signature>
    </SlaveInformation>

    <DataRecord id="0">
        <Function>Instantaneous value</Function>
        <Unit>Energy (10 Wh)</Unit>
        <Value>686648</Value>
    </DataRecord>

    <DataRecord id="1">
        <Function>Instantaneous value</Function>
        <Unit>Energy (10 Wh)</Unit>
        <Value>686648</Value>
    </DataRecord>

<MBusData>

And here's the XSL Template that refuses to work:

<xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

    <xsl:output method="text" encoding="UTF-8"/>

    <xsl:template match="/">
        <xsl:for-each select="Datarecord">
            <xsl:value-of select="@Value"/>
        </xsl:for-each>
    </xsl:template>

</xsl:stylesheet>

I tried to run it with:

xsltproc xslfile xmlfile

Hope you can help...

Upvotes: 1

Views: 516

Answers (1)

michael.hor257k
michael.hor257k

Reputation: 117083

First, your XML input is not well formed: the last <MBusData> tag needs to be a closing tag </MBusData>.

Next, this:

<xsl:template match="/">
        <xsl:for-each select="Datarecord">

selects nothing. You are in the context of the / root node, and there are no Datarecord elements that are children of /. Moreover, XML is case-sensitive and Datarecord is not the same thing as DataRecord. So you need to change this to:

<xsl:template match="/">
        <xsl:for-each select="MBusData/DataRecord">

Finally, Value is a child of Datarecord, not an attribute - so you need to change this:

<xsl:value-of select="@Value"/>

to:

<xsl:value-of select="Value"/>

Edit:

THX, it works, but what if I only want to read only one specific DataRecord, lets say id="1"?

Then you should not use for-each. Instead, try:

<xsl:template match="/">
    <xsl:value-of select="MBusData/DataRecord[@id='1']/Value"/>
</xsl:template>

Upvotes: 2

Related Questions