Search code examples
xmlchartsjasper-reports

Jasperreports create chart with 2 series from 2 different datasets from XML


I can't manage to add two series to my chart in Jaspersoft Studio. Here a simplified version of my XML:

<test>
    <result name="A">
        <point x="10" y="-5"/>
        <point x="20" y="-1"/>
        <point x="30" y="3"/>
    </result>
    <result name="B">
        <point x="11" y="-5"/>
        <point x="19" y="-1"/>
        <point x="25" y="3"/>
    </result>
</test>

So I want to put 2 series on my chart, one for results A and one for results B. I have created a dataset for A:

<subDataset name="res_a">
        <property name="com.jaspersoft.studio.data.defaultdataadapter" value="XMLAdapter"/>
        <queryString language="xPath">
            <![CDATA[/test/result[@name = 'A'/point]]]>
        </queryString>
        <field name="x_a" class="java.lang.String">
            <fieldDescription><![CDATA[@x]]></fieldDescription>
        </field>
        <field name="y_a" class="java.lang.String">
            <fieldDescription><![CDATA[@y]]></fieldDescription>
        </field>
</subDataset>

And added it to the chart:

<xyLineChart>
        <chart evaluationTime="Report">
            <reportElement x="0" y="0" width="780" height="340"/>
        </chart>
        <xyDataset>
            <dataset>
                <datasetRun subDataset="res_a">
                    <dataSourceExpression><![CDATA[((net.sf.jasperreports.engine.data.JRXmlDataSource)$P{REPORT_DATA_SOURCE}).subDataSource("/test/result[@name = 'A']/point")]]></dataSourceExpression>
                </datasetRun>
            </dataset>
            <xySeries>
                <seriesExpression><![CDATA["RESULTS A"]]></seriesExpression>
                <xValueExpression><![CDATA[Double.parseDouble( $F{x})]]></xValueExpression>
                <yValueExpression><![CDATA[Double.parseDouble( $F{y})]]></yValueExpression>
            </xySeries>
        </xyDataset>
    [...]
</xyLineChart>

This works fine and shows one curve on the chart. But how do I add the other results to the same chart? Do I create a second dataset? Outside or inside the chart? I tried several things and they all didn't work, it gave me errors each time.

Any help is appreciated!


Solution

  • You can't use two datasets for a chart. What you can do is to use a single dataset for both result A and result B.

    To do that, you'll first need to select both A and B nodes:

    <dataSourceExpression><![CDATA[((net.sf.jasperreports.engine.data.JRXmlDataSource)$P{REPORT_DATA_SOURCE}).subDataSource("/test/result[@name = 'A' or @name = 'B']/point")]]></dataSourceExpression>
    

    Then create a field in the subdataset for the result name:

    <field name="result" class="java.lang.String">
        <fieldDescription><![CDATA[../@name]]></fieldDescription>
    </field>
    

    And then use the result field as chart series:

    <seriesExpression><![CDATA["RESULTS " + $F{result}]]></seriesExpression>