views:

31

answers:

1

I have a script like this:

var xml_http_request = new XMLHttpRequest();
xml_http_request.addEventListener('readystatechange', PageReady, false);
xml_http_request.overrideMimeType("text/xml");
xml_http_request.open('GET', "index.xml", true);
xml_http_request.send(null);

function PageReady()
{
    if(this.readyState != 4)
        return;
    var Doc = this.responseXML;
    alert(Doc.getElementById("page1"));
}

and index.xml file:

<?xml version="1.0" encoding="UTF-8"?>
<page id="page1">
<layer id="layer1">
    <hook to="page1" edge="top" distance="10px" />
    <hook to="page1" edge="left" distance="10px" />
    <hook to="page1" edge="right" distance="10px" />
    <hook to="page1" edge="bottom" distance="10px" />
</layer>
</page>

The alert that I see contains the message: null which is incorrect, because the document got element with id page1.
Looking in Google Chrome's Inspector, the Doc has a single child with attribute id set to page1.
Why doen't it work?

+1  A: 

It's because getElementById normally only works on html/xhtml. You could get around this by modifying your data so that it is in xhtml format instead of plain XML, or could could try adding some XML DTD to your file so that getElementById should work.

Something like:

<!ELEMENT page>
<!ATTLIST page id ID>

Check here for more information.

Ryan Peden
Added the following line: <!DOCTYPE page SYSTEM "dtd.dtd">And the dtd.dtd file: <!ELEMENT page (layer)*> <!ELEMENT layer (layer|hook)*> <!ELEMENT hook EMPTY> <!ATTLIST layer id ID> <!ATTLIST page id ID> <!ATTLIST hook id ID>It didn't work, and in inspector resources, the dtd.dtd file wasn't even loaded.
Dani