简体   繁体   中英

XML Parsing using JavaScript

Here's an XML snippet:

<appSettings>
  <add key="val1" value="val2"/>

The XML document is loaded in memory, ready to be parsed.

How would you get and write the value of "val2" to the web page?

Thanks, rodchar

Post Comments:
I'm getting .selectSingleNode is not a function:

<script type="text/javascript">
    if (window.XMLHttpRequest)
      {
        xhttp=new window.XMLHttpRequest()
      }
    else
      {
        xhttp=new ActiveXObject("Microsoft.XMLHTTP")
      }
    xhttp.open("GET","test.xml",false);
    xhttp.send("");
    xmlDoc=xhttp.responseXML;

    var node = xmlDoc.selectSingleNode("/appSettings/add[@key='Key']");
    alert(node.getAttribute("value"));


</script>

Try this:

var node = xmlDoc.selectSingleNode("/appSettings/add[@key='val1']");
alert(node.getAttribute("value"));
var xmlDoc;
if (typeof DOMParser !== 'undefined') {
  xmlDoc = (new DOMParser).parseFromString(xmlText, 'text/xml');
} else {
  xmlDoc = new ActiveXObject('Microsoft.XMLDOM');
  xmlDoc.async = 'false';
  xmlDoc.loadXML(xmlText);
}

Use jQuery, it's so much nicer.

  $(request.responseXML).find("add").each(function() {
      var marker = $(this);
      var key = marker.attr("key");
      var value = marker.attr("value");
  });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM