开发者

Problems Parsing XML Output of CGI

I have requested the data from our CGI in XML format. I do this asynchronously and have a callback function like so:

var serverData;
function serverDataCallback(event) {
    if (event.target.readyState === 4) {
        if(event.target.status === 200) {
            var serverData = event.target.responseXML;
    }
}

If I conso开发者_开发知识库le.log the event, I get an XMLHttpRequestProgressEvent.

The target.responseXML is exactly what I want, it looks like this in the Chrome debugging console of type Document:

<Params>
    <VCA>
        <Ch0>
            <enable>yes</enable>
        </Ch0>
    </VCA>
</Params>

However, I have no idea how to process this information! I have had a look at lots of tutorials and the following does not work:

serverData.getElementByTagName('Ch0')[0].getElementByTagName('enable')[0]

There is just an exception saying that getElementByTagName does not exist.

If I console.log the serverData it is reported as a Document

I've never done an XML HTTP Request to return XML before, so don't really know what I'm doing! Could anyone shed some light?


If you want to use the DOM (like you are in your example), you need to walk down the element tree just as elaborately as the XML document is. You also need to spell the functions correctly; it's called getElementsByTagName and not getElementByTagName since there's nothing unique about a tag name and thus the method will return an array of matching elements. A DOM solution would be something like this:

var xhr = new XMLHttpRequest();

xhr.onreadystatechange = function() {
  if ((this.readyState == 4) && (this.status == 200)) {
    var paramsElement = this.responseXML.getElementsByTagName('Params')[0];
    var vcaElement = paramsElement.getElementsByTagName('VCA')[0];
    var chElement = vcaElement.getElementsByTagName('Ch0')[0];
    var enableElement = chElement.getElementsByTagName('enable')[0];
    var enable = enableElement.data;

    console.debug(enable);
  }
};

xhr.open('GET', 'test.xml');
xhr.send();

There should of course be a lot of error checking here (each call to getElementsByTagName may return null), but it will hopefully get you started. I would, however, encourage you to not use the DOM or XmlHttpRequest directly, but instead an abstraction like jQuery:

$.get('test.xml', function(data, textStatus, xhr) {
  var $enable = $(data).find('Params VCA Ch0 enable');
  var enable = $enable.text();
  console.debug(enable);
}, 'xml');

As you can see, it's much less code and you get nice translation from the XML to a jQuery object that is a lot more powerful than DOM objects.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜