0

I need to get the value of "templatedata" (RK1S) using JavaScript.

<additional_info>
<Param name="srno" value="B4745" />
<Param name="Device" value="Opn" />
<Param name="Support" value="0" />
<Param name="templatedata" value="Rk1S"/>
</additional_info>

I tried with the following script but I'm getting undefined.

var text=" <additional_info>
    <Param name="srno" value="B4745" />
    <Param name="Device" value="Opn" />
    <Param name="Support" value="0" />
    <Param name="templatedata" value="Rk1S"/>
    </additional_info>";

if (window.DOMParser) {
  parser = new DOMParser();
  xmlDoc = parser.parseFromString(text,"text/xml");
} else {
  xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
  xmlDoc.async = false;
  xmlDoc.loadXML(text); 
} 


var txt;
var x = xmlDoc.getElementsByTagName("additional_info");
alert(x[0].value);
var y=x.getAttribute("Param name")
txt = y.nodeValue;
alert(txt);

1
  • Welcome to SO! Check escape characters in your string. You need single quotes, backticks or backslashes. Commented Sep 14, 2018 at 6:48

1 Answer 1

2

All you need is querySelector for the element you want, which can be selected with Param[name="templatedata"]. Use a template literal instead of double quotes to define a string over multiple lines, and use getAttribute('value') instead of .value, because .value only works for input-like elements:

var text = `<additional_info>
<Param name="srno" value="B4745" />
<Param name="Device" value="Opn" />
<Param name="Support" value="0" />
<Param name="templatedata" value="Rk1S"/>
</additional_info>`;

let parser;
let xmlDoc;
if (window.DOMParser) {
  parser = new DOMParser();
  xmlDoc = parser.parseFromString(text, "text/xml");
} else {
  xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
  xmlDoc.async = false;
  xmlDoc.loadXML(text);
}
const param = xmlDoc.querySelector('Param[name="templatedata"]');
console.log(param.getAttribute('value'));

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.