如何在jquery中读取xml解析并在html元素中显示

时间:2017-02-16 10:02:48

标签: jquery html xml parsing service

我正在尝试在html中显示已解析的xml数据。我已成功从Web服务调用数据并将dataType设置为xml。但是,下面的代码没有错误,它没有将解析的xml数据显示为html。我做错了什么?

XML数据:

<?xml version='1.0' ?>
<string>
    <DriverInfo xmlns=\"http://tempuri.org/DriverInfo.xsd\">
        <Driver>
            <ID>-1</ID>
                <driver_code>DRIVER01</driver_code>
                <driver_name>DRIVER01 Name</driver_name>
            <transtamp>2017-02-16T14:41:09.9655914+08:00</transtamp>
        </Driver>
    </DriverInfo>
</string>

已成功检索解析的XML数据的整个代码:

$.ajax({
    url: domainName + "GetDriverXml", 
    method: "GET",
    data: {wsCodeCrypt:"MULARIDEWS", caUid: "mularide", caPwd:"VAt_-tg4%Z5pcpct", 
    driverCode:"DRIVER01"},
    cache: false,
    dataType: "xml",
    success: function(data) {
        var xmlDoc = $.parseXML($(data).text());
            var $xml = $(xmlDoc);

            var $driver = $xml.find("Driver");

            $driver.each(function(){

            var driverCode = $(this).find('driver_code').text(),
                driverName = $(this).find('driver_name').text();

            $("#driverDet" ).append('<li>' +driverCode+ ' - ' +driverName+ '</li>');

            });         
    }          
});

HTML

<ul id="driverDet"></ul>

非常感谢任何帮助。

编辑:发现madalin ivascu指出的问题,“驱动程序”需要更改为“驱动程序”。还更新了将'data'解析为.text的代码,然后就有了光!

1 个答案:

答案 0 :(得分:0)

在查找选择器中将驱动程序更改为驱动程序

var xml = "<?xml version='1.0' ?><string><DriverInfo xmlns=\"http://tempuri.org/DriverInfo.xsd\"> <Driver><ID>-1</ID><driver_code>DRIVER01</driver_code><driver_name>DRIVER01 Name</driver_name><transtamp>2017-02-16T14:41:09.9655914+08:00</transtamp></Driver><Driver><ID>-1</ID><driver_code>DRIVER01</driver_code><driver_name>DRIVER01 Name</driver_name><transtamp>2017-02-16T14:41:09.9655914+08:00</transtamp></Driver></DriverInfo></string>",
  xmlDoc = $.parseXML(xml);
$(xmlDoc).find('Driver').each(function() {
  var driverCode = $(this).find('driver_code').text(),
    driverName = $(this).find('driver_name').text();

  $("#ProfileList").append('<li>' + driverCode + ' - ' + driverName + '</li>');

});

演示:https://jsfiddle.net/814yhL3m/