generate javascript using xml and xsl

2019-07-26 08:03发布

问题:

I have tried every solution I found on here and even a larger Google search but nothing seems to work. Here is my problem... I have data that is in XML that I would like to visualize using the Google Visualization API. I was hoping I could simply use XSL to generate what I need instead of doing anything with data sources (I have my reasons). But the javascript code does not show up in my output. Is this even possible?

My XML

<DocumentElement>
  <QueryResults>
    <Year>2000</Year>
    <Population>100000</Population>
  </QueryResults>
  <QueryResults>
    <Year>2001</Year>
    <Population>105000</Population>
  </QueryResults>
</DocumentElement>

My XSL file

<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="html" encoding="utf-8"/>
<xsl:template match="/">

    <script type="text/javascript" src="http://www.google.com/jsapi"></script>     
    <script type="text/javascript">
        google.load('visualization', '1', {packages:['barchart']});
        google.setOnLoadCallback(drawChart);

        function drawChart() {
            var data = new google.visualization.DataTable();

            data.addColumn('string', 'Year');
            data.addColumn('string', 'Population');
            data.addRows(2); // hard-coded for testing

            <xsl:for-each select="DocumentElement/QueryResults">
                data.setValue(0, 0, '<xsl:value-of select="Year"/>');
                data.setValue(0, 1, '<xsl:value-of select="Population"/>');                 
            </xsl:for-each>

            var chart = new google.visualization.BarChart(document.getElementById('chart_div'));
            chart.draw(data, {width: 400, height: 240, is3D: true, title: 'Population'});
        }
    </script>

    <div id="chart_div">&#160;</div>

</xsl:template>
</xsl:stylesheet>

My output

<!-- notice no javascript -->
<div id="chart_div"> </div>

回答1:

What does the line in your XML that includes the XSL file look like? I added these two lines to the top of the XML:

<?xml version="1.0" encoding="utf-8"?>
<?xml-stylesheet type="text/xsl" href="test.xsl"?>

The result was correct, though the graph didn't actually show the data properly. It was at least called. alt text http://i21.photobucket.com/albums/b296/Bonus_Eruptus/so/xml_chart.jpg