简体   繁体   中英

XML Tag name reading in JavaScript

I need help to read the name of an XML tag and save it in a variable in order to compare it with other values.

This is an example XML snippet showing what I need:

<H01></H01>
<H02></H02>
<H03></H03>

I need to get the H[number] to be able to compare it with another H[number] .

I'm answering this in Node.js context since you have tagged the question so.

Use fast-xml-parser . Here's an example:

var parser = require('fast-xml-parser');
var json = parser.parse(xmlData,options);

You'll end up with an object that's easy to use in your program. You can also validate your XML, etc. Make sure to check out the readme .

Here is a way to view them with JS inside of HTML. I had to wrap the H# tags in another tag to make them be valid XML. First save them into an array.

     <!DOCTYPE html>
<html>
<body>
<p id="outTags"></p>

<p id="outArrayAsList"></p>

<script>
var parser, xmlDoc;
var text = "<wrap><H01>1</H01>" +
  "<H02>2</H02>" +
  "<H03>3</H03></wrap>";

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

var tags = [];

var x = xmlDoc.documentElement.childNodes;
for (i = 0; i < x.length ;i++) {
    tags[i] = x[i].nodeName;
}
document.getElementById("outTags").innerHTML = tags;
// or you could iterate over the array elements 
var text = "<ul>";
for (i = 0; i < tags.length; i++) {
    text += "<li>" + tags[i] + "</li>";
}
text += "</ul>";
document.getElementById("outArrayAsList").innerHTML = text;
</script>
</body>
</html>

Output looks like:

H01,H02,H03

    H01
    H02
    H03

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