使用jQuery解析多个XML文件并显示为分层树

时间:2014-05-18 12:35:52

标签: jquery ajax xml treeview

jquery和ajax的新手,我试图创建一个html页面,它将在分层树视图中显示来自两个xml文件的信息。 Categories.xml将定义所有各种产品的类别,products.xml将包含所有单个产品数据。 ' Products.xml'共享名为' categoryID'的外键。与' categories.xml'。在这个阶段,我根本无法将任何XML数据加载到页面中,更不用说获得分层树视图了。我已经搜索了几个小时的答案,但我似乎无法找到有关加载两个xml文件并使用两个文件中的信息填充树的任何信息。我的代码如下:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<script type="text/javascript">
$(document).ready(function() {
    $("#loadBtn").click(function() {
        $.ajax({
            type: "GET",
            url: "products.xml",
            datatype: "xml",
            error: function(jqXHR, textStatus, errorThrown) {
                console.log('Error: ' + errorThrown);
            },
            success: function(xml) {
                console.log('AJAX Request successful.');

                var productTable= '';
                productTable += '<table id="productTable" cellspacing="2" border="0">' ;

                productTable += '<thead><td>Product ID</td><td>Name</td><td>Quantity Per Unit</td><td>Unit Price</td></thead>';

                $(xml).find('product').each(function(){
                    productTable += '<tr>';
                    productTable += '<td>';
                    productTable += $(this).find('ProductId').text();
                    productTable += '</td>';

                    productTable += '<td>';
                    productTable += $(this).find('ProductName').text();
                    productTable += '</td>';

                    productTable += '<td>';
                    productTable += $(this).find('QuantityPerUnit').text();
                    productTable += '</td>';

                    productTable += '<td>';
                    productTable += $(this).find('UnitPrice').text();
                    productTable += '</td>';

                    productTable += '</tr>';
                });
                productTable += '</table>';
                $("#products").append(productTable);

            }
        });
    });
});
</script>
<title>Products</title>
</head>

<body>
Click to Load:
<input type="button" id="loadBtn" value="Products"/>
<br/><br/>
<div id=products></div>
</body>
</html>

和我的XML文件(产品)

<?xml version="1.0" encoding="UTF-8"?>
<ProductsRoot>
    <Products>
        <ProductID>1</ProductID>
        <ProductName>Chai</ProductName>
        <CategoryID>1</CategoryID>
        <QuantityPerUnit>10 boxes x 20 bags</QuantityPerUnit>
        <UnitPrice>18</UnitPrice>
    </Products>
    <Products>
        <ProductID>2</ProductID>
        <ProductName>Chang</ProductName>
        <CategoryID>1</CategoryID>
        <QuantityPerUnit>24 - 12 oz bottles</QuantityPerUnit>
        <UnitPrice>19</UnitPrice>
    </Products>
    <Products>
        <ProductID>3</ProductID>
        <ProductName>Aniseed Syrup</ProductName>
        <CategoryID>2</CategoryID>
        <QuantityPerUnit>12 - 550 ml bottles</QuantityPerUnit>
        <UnitPrice>10</UnitPrice>
    </Products>
</ProductsRoot>

和类别的XML

<?xml version="1.0" encoding="UTF-8"?>
<CategoriesRoot>
    <Categories>
        <CategoryID>1</CategoryID>
        <CategoryName>Beverages</CategoryName>
        <Description>Soft drinks, coffees, teas, beer, and ale</Description>
    </Categories>
    <Categories>
        <CategoryID>2</CategoryID>
        <CategoryName>Condiments</CategoryName>
        <Description>Sweet and savory sauces, relishes, spreads, and seasonings</Description>
    </Categories>
    <Categories>
        <CategoryID>3</CategoryID>
        <CategoryName>Confections</CategoryName>
        <Description>Desserts, candies, sweetbreads</Description>
    </Categories>
    <Categories>
        <CategoryID>4</CategoryID>
        <CategoryName>Dairy Products</CategoryName>
        <Description>Cheeses</Description>
    </Categories>
</Categories Root>

我已经附加了xml以节省空间,但这是一般的想法...

任何人都可以帮助我弄清楚我做错了什么吗?

提前致谢!

2 个答案:

答案 0 :(得分:1)

这是一个简单的例子,说明如何使用两个ajax调用组合多个XML数据。这应该会让你走上正轨;) https://gist.github.com/marcoramires/a88c85cea3690c7cbb73

<!doctype html>
<html class="no-js" lang="">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Untitled Document</title>
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
    $(document).ready(function () {
        $('#menu_wrapper').append('<ul></ul>');
        $.ajax({
            type: 'GET',
            url: 'Categories.xml',
            dataType: 'xml',
            success: function (data) {
                console.log('Fetching categories...');
                $(data).find('Categories').each(function () {
                    if($(this).children().length)
                    {
                        var categoryID = $(this).find('CategoryID').text();
                        var categoryName = $(this).find('CategoryName').text();
                        var description = $(this).find('Description').text();

                        var html = '<a href="#'+ categoryName +'" title="' + description + '">' + categoryName + '</a>';
                        $('<li id="' + categoryID + '"></li>').html(html).appendTo('#menu_wrapper ul');
                    }
                });
            },
            error: function () {
                console.log('An error occurred while processing Categories XML file.');
                //alert('An error occurred while processing Categories XML file.');
            }
        }).done(function(){
            console.log('... done.');
            console.log('Fetching products...');
            getProducts();
        });

        var getProducts = function(){
            $.ajax({
                type: 'GET',
                url: 'Products.xml',
                dataType: 'xml',
                success: function (data) {
                    $(data).find('Products').each(function () {
                        if($(this).children().length)
                        {
                            var productID = $(this).find('ProductID').text();
                            var productName = $(this).find('ProductName').text();
                            var categoryID = $(this).find('CategoryID').text();
                            var qtyPerUnity = $(this).find('QuantityPerUnit').text();
                            var unitPrice = $(this).find('UnitPrice').text();

                            var html = '<a href="#Product='+ productID +'" title="' + productName + ',' + unitPrice + '">' + productName + '</a>';
                            var categoryElement =  document.getElementById(categoryID);
                            var subList = document.getElementById('Sub_' + categoryID );
                            if(subList == null)
                            {
                                $('<ul id="Sub_' + categoryID + '"></ul>').appendTo(categoryElement);
                                $('<li></li>').html(html).appendTo('#Sub_' + categoryID);
                            }
                            else
                            {
                                $('<li></li>').html(html).appendTo(subList);
                            }
                        }
                    });
                },
                error: function () {
                    console.log('An error occurred while processing Products XML file.');
                    //alert('An error occurred while processing Products XML file.')
                }
            }).done(function(){
                console.log('... done loading content tree.');
            });
        }
    });
</script>
</head>
<body>
    <div id="menu_wrapper"></div>
</body>
</html>

答案 1 :(得分:0)

我不知道为什么.find();不适合您,但是,您也可以使用getElementsByTagName()在xml上获取这些值。考虑这个例子:

<table border="1" cellpadding="10">
    <thead>
        <tr>
            <th>Product ID</th>
            <th>Product Name</th>
            <th>Category ID</th>
            <th>Quantity Per Unit</th>
            <th>Unit Price</th>
        </tr>
    </thead>
    <tbody id="values">

    </tbody>
</table>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){

    $.ajax({
        url: 'products.xml',
        dataType: 'xml',
        success: function(response) {
            var values = response.getElementsByTagName('Products');
            $.each(values, function(index, element){
                var product_id = element.getElementsByTagName('ProductID')[0].innerHTML;
                var product_name = element.getElementsByTagName('ProductName')[0].innerHTML;
                var category_id = element.getElementsByTagName('CategoryID')[0].innerHTML;
                var quantity = element.getElementsByTagName('QuantityPerUnit')[0].innerHTML;
                var unit_price = element.getElementsByTagName('UnitPrice')[0].innerHTML;

                var table_data = '<tr>';
                table_data += '<td>'+product_id+'</td>';
                table_data += '<td>'+product_name+'</td>';
                table_data += '<td>'+category_id+'</td>';
                table_data += '<td>'+quantity+'</td>';
                table_data += '<td>'+unit_price+'</td>';
                table_data += '</tr>';

                $('#values').append(table_data);
            });
        }
    });

});
</script>