简体   繁体   中英

Use RegExp to read value from xml

I have an XML doc with key and value pairs and I want to extract the value for a particular pair.

I tried:

var dat1 = xmlDoc.replace(/.*<d0>([^<]*)<\/d0>.*/, "$1");

The above gives me value for d0 in dat1 , but for subsequent data retrieval, it doesn't return correct values.

So, the first question is: What method can I use to extract values from an XML doc by using regexp (yes, I need to use regedt)?

Is the replace method used above correct?

Update: I have following xml string coming in:

<dataVal><d0>123</d0><d1>456</d1></dataVal>

Now, the inbuilt xml parsing methods works for me for mozilla and chrome but for IE it is not able to parse the string. Example, on IE it gets null if I use:

var dat1 = xmlDoc.getElementsByTagName('d0')[0].firstChild.nodeValue

It is not recommended to parse XML with regular expressions. Use an XML parser instead. Basic example with jQuery (obviously requires jQuery):

var xml = "<music><album>Beethoven</album></music>";

var result = $(xml).find("album").text();

Example using browser's built in DOM:

<!DOCTYPE html>
<html>
    <body>
        <script>
            text = "<bookstore><book>";
            text = text + "<title>Galapagos</title>";
            text = text + "<author>Kurt Vonnegut</author>";
            text = text + "<year>1985</year>";
            text = text + "</book></bookstore>";
            var xmlDoc, bookTitle;
            if (window.DOMParser) {
                parser = new DOMParser();
                xmlDoc = parser.parseFromString(text, "text/xml");
            } else // Internet Explorer
            {
                xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
                xmlDoc.async = false;
                xmlDoc.loadXML(text);
            }
            bookTitle = xmlDoc.getElementsByTagName("title")[0].childNodes[0].data;
            document.write(bookTitle);
        </script>
    </body>
</html>

Obligatory link as to why using regexes with XML (and HTML) is a bad idea: RegEx match open tags except XHTML self-contained tags

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM