XML Parsing in Javascript in Generic Mode

2019-08-02 08:07发布

问题:

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 .

回答1:

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:

xml.XMLDocument.selectSingleNode('MESSAGE/PAYLOAD/PRELOGIN/TABLE/FIRSTNAME');

If you are using a jQuery it will be more easier to retrieve it in this way:

var firstName = $(xmlString).find('FIRSTNAME')[0].innerText;

Hope this was helpful.



回答2:

The DOM method getElementsByTagName returns a NodeList object, which is an array, even if only one element is found. You have to select the first one:

var message   = xml.documentElement.getElementsByTagName("MESSAGE")[0];

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 one LASTNAME you can extract them using:

var firstname = xml.documentElement.getElementsByTagName("FIRSTNAME")[0];
var lastname  = xml.documentElement.getElementsByTagName("LASTNAME")[0];