简体   繁体   中英

How to use XML Parser and get element by tagName when tag contains embedded element inside?

I'm using XMLParser to get data from a tag.

This tag is like this :

<tagName elem="XXX"></tagName>

I want to get : XXX

According to documentation, I'm doing like :

    parseMyXML = new DOMParser();
    xmlDoc = parseMyXML.parseFromString(contentXML,"text/xml");

    var code_XXX = xmlDoc.getElementsByTagName("tagName")[0].childNodes[0].nodeValue;

I have an error : Uncaught (in promise) TypeError: Cannot read property 'nodeValue' of undefined

What I need is to go into tagName and to get the contain of elem

这是一个属性,而不是子节点。

xmlDoc.getElementsByTagName("tagName")[0].getAttribute("elem");

With jQuery you can do something like this.

    var $xml = $.parseXML(xml),
       value = $xml.find('tagName').text();

if you're using plain JS you should parse xml like this.

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

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