This is only my first AJAX based application so this may be a trivial
question but I cannot find any way of getting at the data I want.
So, I have an XML file of the form:
<data>
<dataelement> // one or more instances of this
.
some data
.
<status>
.
some status information
.
</status>
</dataelement>
<status>
.
some status information
.
</status>
</data>
The significant feature is that both the enclosing <data> and each
<dataelement> have <status> elements that are identical in format so I
want to keep the <status> tag.
I can use getElementsByTagName to extract all the <dataelements> and
then use getElementByTagName to get all <status> elements in each
<dataelement>. There should only be one so I can use FirstChild to
access it.
Using getElementsByTagName on <data> gets me an array containing all
<status> elements including those of the child <dataelements>s. What I
need is some means to extract from <data> only those <status> elements
that are directly children of the <data> and not those that are children
of the child <dataelement>s. I could probably use LastChild to get what
I want but cannot guarantee that the <status> will necessarily come
after the <dataelement>s.
I hope this is clear.
Thanks,
Andrew
This is actually a DOM question, which is an interface that's
implemented in lots of languages, so it's not strictly JS. Also,
XMLHttpRequest is unfortunately named - XML is quite heavyweight for
most Ajax applications; JSON is much easier to work with in
JavaScript, and takes much less code to traverse. Plus, it's easy for
server-side languages to parse; there are lots of free parsing
libraries out there for your language of choice, if you have the
misfortune to not be working in Python on the server
. If you
haven't yet, I'd recommend taking a look at JSON.
But to answer your question, you need node.childNodes. Be aware that,
as you iterate through this NodeList, you'll have to check the
NodeType property to ensure that it equals 1 (node.ELEMENT_NODE),
because childNodes also may include text nodes, comment nodes, CDATA
nodes, etc., none of which have a tagName property. (Alternatively,
you may traverse the childNodes as a linked list, starting with
node.firstChild, then assigning successively node = node.nextSibling
until you reach node.lastChild). Let me know if you need code samples
here. Good luck!
-David