Not sure why that happens but when I parse the XML I get as a response to the AJAX post, it sometimes displays an error (null object) if the element exists but empty ?
The XML I get contains some records that have optional fields. Any ideas?
Sorry, I didn't add my code to the post. Here is a sample of the XML and the JS code: [CODE]<root> [INDENT]<item> [INDENT][INDENT]<date>2009-05-10</date> <title />[/INDENT][/INDENT] </item>[/INDENT] </root>
1. var response = xmlHttp.responseXML.documentElement; 2. var items = response.getElementsByTagName('item'); 3. var title = items[0].getElementsByTagName('title')[0].firstChild.data; 4. var date = items[0].getElementsByTagName('date')[0].firstChild.data;[/CODE]
The above XML causes an error (null object) at statement #3. It works fine if the title element has a value (e.g. <title>Test</title>).
That is not a valid XML syntax... That is a sort of XHTML like-syntax, which is something else. What is that [B]<title />[/B] for? At least make it [B]<title></title>[/B]
mesh2005, I think the problem comes when you use ".firstChild.data" on the title node. Notice that the title node is empty. It has no child nodes, so firstChild will be null. Which means when you use ".data", you're using it on a null value. Probably you'll need to start using some conditional expressions.
var titleNode = items[0].getElementsByTagName('title')[0]; var title = titleNode.firstChild ? titleNode.firstChild.data : "";
@KorAug 14.2009 — #There's exactly the place where it is written: "the empty-element tag SHOULD be used, and SHOULD [COLOR="Blue"]only[/COLOR] be used, for elements which are declared EMPTY." From this line I always understood that empty-element tags are [I]XHTML only[/I], because I see no reason for using EMPTY elements in XML documents. I always took empty-element tags as XML extensions towards XHTML, not an XML standalone syntax.
This is easy to be seen whenever you want do declare an empty element using an XML schema. In the end the code will avoid the < /> notation:
@Jeff_MottAug 14.2009 — #But that might not make the XML document well formatted as well.[/quote]Empy-element tags do not affect either well-formdness or validity.
I always understood that empty-element tags are XHTML only, because I see no reason for using EMPTY elements in XML documents.[/quote]You'll find empty elements in RSS, Atom and XSL documents, to name a few. They're actually quite common.
I always took empty-element tags as XML extensions towards XHTML, not an XML standalone syntax.[/quote]Well... that's just not the case.