How do I get the full value(including any additional tags) from .text of an XML key / Value using Javascript

So I’ve been stumped on a particular problem.

I’ve got an XML file which contains a key value pair.

My basic goal is to just enter a key and the corresponding value is to be displayed using an alert box.

My XML file is as follows:

<?xml version="1.0" encoding="UTF-8"?>
<properties>
<name key="amit"><person><b1>Amit</b1></person> </name>
<name key="Peter">Morris </name>
</properties>

My Script file is as follows:

var xmlDoc;
function getValue(key)
{
    xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.load("properties.xml");
if(xmlDoc.readyState == 4)
{
   for(var i=0;i<xmlDoc.documentElement.childNodes.length;i++)
   {
    if(xmlDoc.documentElement.childNodes[i].attributes.getNamedItem("key").nodeValue==key)
    {
        alert(xmlDoc.documentElement.childNodes[i].nodeValue);
        return xmlDoc.documentElement.childNodes[i].text;
    }
   }

 }
}

My html file is as follows:

<html>
    <head>
    <script src="script.js"></script>
</head>
<body>
    <script>
        var value=getValue("amit");
        alert(value);
    </script>
</body>
</html>

When I run my code, if the value I pass is ‘Peter’ then my alert box shows me ‘Morris’. Which I expected.

But when I pass the value ‘amit’, the alert box shows me ONLY ‘Amit’. It does not show me

  <person><b1>Amit</b1></person> 

I need the full value to be printed.

Can someone kindly let me know what I’ve missed or how I can go about doing this?


Source: xml

Leave a Reply