在Ajax中解析xml响应无法正常工作

时间:2013-04-10 16:41:06

标签: jquery xml parsing

我正在尝试解析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" />
<title>XML parsing cluster state </title>

<script language="javascript" src="js/jquery.js"></script>
<script language="javascript">


$(document).ready(function()
{
  $.ajax({
    type: "GET",
   // url: "cstate.xml",
      url: "jquery_xml.xml",
    dataType: "xml",
    success: function(xml) { parseXml(xml); }
  });
});

function parseXml(xml)
{
  //find state and print the state

    //test 1
  $(xml).find("state").each(function()
  {
    $("#output").append($(this).text() + "<br />");
  });

//test 2    
  $(xml).find("cluster_info").each(function()
  {
    $("#output").append($(this).find("state").text());
    $("#output").append(": " + $(this).find("state").text() + "<br />");
  });

}
</script>


</head>

<body>


<div id="output"></div>

</body>
</html>

XML

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<cluster_info>
    <nodes>
        <entry>
            <key>Standby stuff</key>
            <value>
                <available_versions>
                    <available_version>62</available_version>
                </available_versions>
                <current_version>62</current_version>
            </value>
        </entry>
    </nodes>
    <target_state>
        <available_versions>
            <available_version>62</available_version>
        </available_versions>
        <current_version>62</current_version>
    </target_state>
    <new_versions>
        <new_version>38</new_version>
        <new_version>37</new_version>
    </new_versions>
    <removable_versions />
    <state>STABLE</state>
</cluster_info>

2 个答案:

答案 0 :(得分:0)

XML中存在错误:

<state>STABLE</cluster>

应该是

<state>STABLE</state>

答案 1 :(得分:0)

Fiddle

这项工作没问题。

$(xml).find('state').each(function () {
    $('body').text($(this).text());
});
相关问题