简体   繁体   中英

How to parse this XML using javascript DOM?

This is my xml

<colors>
<SET name="temp">
    <menu>#9c7db5</menu>
    <menuTxt>#ffffff</menuTxt>
    <tH>#FFF</tH>
    <tHTxt>#000</tHTxt>
    <head>#919191</head>
    <headTxt>#ffffff</headTxt>
    <label>#2e2e2e</label>
    <but>#8f8f8f</but>
    <butTxt>#ffffff</butTxt>
    <footer>#FFF</footer>
    <footTxt>#000</footTxt>
    <backT>#FFF</backT>
</SET>
<SET name="footercheck">
    <menu>#6492c4</menu>
    <menuTxt>#ffffff</menuTxt>
    <tH>#FFF</tH>
    <tHTxt>#000</tHTxt>
    <head>#4275b3</head>
    <headTxt>#ffffff</headTxt>
    <label>#0a0a66</label>
    <but>#3b66a8</but>
    <butTxt>#ffffff</butTxt>
    <footer>#5f90b0</footer>
    <footTxt>#ffffff</footTxt>
    <backT>#FFF</backT>
</SET>
</colors>

User will search by 'name' attributes of <SET> tag. Once the given name is matched with any <SET> tag, I need to get all it's child nodes value. ( <menu><menutxt> ..etc).

This is what I have tried so far,

function parseXML{
                   if (window.XMLHttpRequest)
        {
            xmlhttp=new XMLHttpRequest();
        }
        else
        {
            xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
        }var y;
        xmlhttp.open("GET","style/userTheme.xml",false);
        xmlhttp.send();
        xmlDoc=xmlhttp.responseXML;
        var x=xmlDoc.getElementsByName(iid); //'iid' is user's input
        for (var i = 0; i < x.length; i++) {   
            x[i].childNodes[0].nodeValue
        } 
}

I've checked length of 'X', It's '1'. So It's filtering whole XML to One <SET> . But I don't know how to proceed further. Please drop me an answer if you know.

What you show is not a valid XML. It does not have the first row indicating it's an XML document. The following line is missing, and this could cause you problems while parsing.

<?xml version="1.0" encoding="UTF-8"?>

If you want all the child nodes of a with a given name, you have two ways of doing it.

  • You could iterate all the nodes, find the one with the given name and retrieve all of its children. Modifying your snippet, you could return them as your function's result and do it whatever you like (for example displaying them).

     var childrenNodes = new Array(); for (var i = 0; i < x.length; i++) { childrenNodes[i] = x[i].childNodes[0].nodeValue; } return childrenNodes; 
  • Another way to do it, would be to query the DOM for the specific elements using XQuery or XPath and return the result.

     var result = doc.evaluate('/form/set[name='+iid+']', xmlDoc, null, XPathResult.STRING_TYPE, null); return result; 

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