E4X解析HTTP请求响应XML

时间:2011-10-03 01:05:24

标签: javascript xml xml-serialization xml-parsing e4x

我为目录(地址簿)标记系统整理了一个简单的XML模式。基本结构如下:

<?xml version="1.0" encoding="UTF-8">
<directory
    xmlns="http://example.com"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://example.com directory.xsd">
    <title>An Example Directory Document</title>
    <creator>Lorem Ipsum Dolor</creator>
    <date>September 29, 2011</date>
    <person>
        <firstName>Lorem</firstName>
        <middleName>Ipsum</middleName>
        <lastName>Dolor</lastName>
        <email type="personal">lorem@ipsum.org</email>
        <email type="other">ispum@dolor.org</email>
        <phone type="mobile">(123) 456-7890</phone>
    </person>
</directory>

这是JavaScript(和E4X;实际上只有在PHP $_GET[]$_REQUEST[]变量为真的情况下才会使用它,因为只有Firefox具有不错的E4X支持):

<script type="text/javascript;e4x=1">
var directory;

xmlhttp = new XMLHttpRequest();     
xmlhttp.open('GET', 'http://example.com/directoryExample.xml', true);
xmlhttp.onreadystatechange = (function() {
    if(xmlhttp.readyState === 4) {
        if(xmlhttp.status === 200) {
            directory = xmlhttp.responseXML;
            HandleDirectoryData();
        }
    }
});

function HandleDirectoryData() {
    var container = document.getElementById('output');
    var directoryTitle = directory.title;
    var directoryCreator = directory.creator;
    var directoryDate = directory.date;
    var title = document.createElement('p');
    var creator = document.createElement('p');
    var titleLabel = document.createElement('label');
    var creatorLabel = document.createElement('label');
    title.id = "xmlDirectoryTitle";
    creator.id = "creator";
    titleLabel.for = title.id;
    creatorLabel.for = creator.id;
    titleLabel.textContent = "Title:";
    creatorLabel.textContent = "Creator:";
    titleLabel.appendChild(title);
    creatorLabel.appendChild(creator);
    container.appendChild(titleLabel);
    container.appendChild(creatorLabel);
    for each(var person in XMLData) {
        console.log("Displaying of the person data happens here...");
    }
}

我相信XMLHttpRequest很好,并且它只是解析它有问题。

提前致谢!

0 个答案:

没有答案