【问题标题】:Parse XML with Javascript使用 Javascript 解析 XML
【发布时间】:2012-04-19 12:41:02
【问题描述】:

我正在尝试将 xml 文件解析为 html。 所以我atm跟着去

<script>
  xmlDoc=new window.XMLHttpRequest();
  xmlDoc.open("GET","test",false);
  xmlDoc.send("");
</script>

现在我想“回显”请求,我该怎么做

<?xml version="1.0"?>
<catalog>
   <book id="bk101">
      <author>Gambardella, Matthew</author>
      <title>XML Developer's Guide</title>
      <genre>Computer</genre>
      <price>44.95</price>
      <publish_date>2000-10-01</publish_date>
      <description>An in-depth look at creating applications 
      with XML.</description>
   </book>
</catalog>

【问题讨论】:

    标签: javascript xml parsing


    【解决方案1】:

    试试这个:

    xmlDoc=new window.XMLHttpRequest() || new ActiveXObject("Microsoft.XMLHTTP") || new ActiveXObject("Msxml2.XMLHTTP");
    xmlDoc.onreadystatechange = function(){
        if(xmlDoc.readyState = 4 && xmlDoc.status == 200)  // Success
        {
            document.write(xmlDoc.responseText);
        }
    }
    xmlDoc.open("GET","test",false);
    xmlDoc.send("");
    

    【讨论】:

    • 您好,首先感谢您,目前我无法让它工作。我仍然看到一个空白页面,并且 responseText 仍然是“”有什么想法吗?
    • 在上面的答案中,您需要 == on readyState 但除此之外它是赢家。
    【解决方案2】:

    解析一个 XML 字符串

    以下代码片段将 XML 字符串解析为 XML DOM 对象:

    txt="<bookstore><book>";
    txt=txt+"<title>Everyday Italian</title>";
    txt=txt+"<author>Giada De Laurentiis</author>";
    txt=txt+"<year>2005</year>";
    txt=txt+"</book></bookstore>";
    
    if (window.DOMParser)
    {
      parser=new DOMParser();
      xmlDoc=parser.parseFromString(txt,"text/xml");
    }
    else // Internet Explorer
    {
      xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
      xmlDoc.async=false;
      xmlDoc.loadXML(txt); 
    }
    

    解析 XML 文档

    以下代码片段将 XML 文档解析为 XML DOM 对象:

    if (window.XMLHttpRequest)
    { // code for IE7+, Firefox, Chrome, Opera, Safari
      xmlhttp=new XMLHttpRequest();
    }
    else
    { // code for IE6, IE5
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.open("GET","books.xml",false);
    xmlhttp.send();
    xmlDoc=xmlhttp.responseXML;
    

    【讨论】:

    • 嗨,如果我这样做并使用 document.write(xmlDoc.responseText) 我总是得到“未定义”
    • @FabianBoulegue - 我的代码中有 no xmlDoc.responseText
    • 是的,但没有我不会得到一个空白页 - 如果我只是使用你的代码
    • @FabianBoulegue - 您的输入文件是 有效的 XML 文件且语法正确吗?
    • 将 XML 添加到我的问题中。
      如果我用萤火虫检查响应,我可以看到里面的洞 xml 文本,但它只是没有显示 ^^
    【解决方案3】:

    您可以警告('您的数据或文本在这里')数据并将其显示在弹出窗口中,或者使用各种方法选择一个 div 并使用 .html(data) 插入您的数据。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-09-11
      • 2013-07-10
      • 1970-01-01
      • 1970-01-01
      • 2023-03-07
      • 1970-01-01
      相关资源
      最近更新 更多