Hi I need help in XML Parsing Am new to it
I need to know some tutorials for XML parsing in javascript
I got an XML document which I tried to parse to get the contents of FIRSTNAME
& LASTNAME
from the xml doc but cannot do so
My XML
<MESSAGE>
<HEADER>
<LOGIN>
00986544
</LOGIN>
</HEADER>
<SESSION>
<LATITUDE>
0.0
</LATITUDE>
<LONGITUDE>
0.0
</LONGITUDE>
<TYPE>PRELOGIN</TYPE>
<KEY>PRELOGIN/ID</KEY>
<APP/>
<TRANSACTION>PRELOGIN</TRANSACTION>
</SESSION>
<PAYLOAD>
<PRELOGIN>
<TABLE>
<FIRSTNAME> papapap</FIRSTNAME>
<LASTNAME> hajka</LASTNAME>
</TABLE>
</PRELOGIN>
</PAYLOAD>
</MESSAGE>
Below is the code I tried
var message = xml.documentElement.getElementsByTagName("MESSAGE");
var firstname = xml.documentElement.getElementsByTagName("FIRSTNAME");
var lastname = xml.getElementById("LASTNAME");
I get some HTMLCollection
Object as answer but not the name
Please guide .
I think the problem in you code can be because of the closing tag of the FIRSTNAME node. Replace it with
</FIRSTNAME>
. I think your code will work.If it will not help, try to get the XMLDocument property of your object and call the selectSingleNode method. Something like:
If you are using a jQuery it will be more easier to retrieve it in this way:
Hope this was helpful.
The DOM method
getElementsByTagName
returns aNodeList
object, which is an array, even if only one element is found. You have to select the first one:The method searches the whole tree for all the occurrences of the tag you pass as a parameter, so if you have multiple tags with the same name, even if they are in different subtrees, they will be selected. It's also not the most efficient method. But since you only have one
FIRSTNAME
and oneLASTNAME
you can extract them using: