简体   繁体   English

用JavaScript读取XML标签名称

[英]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. 我需要帮助来读取XML标记的名称并将其保存在变量中,以便将其与其他值进行比较。

This is an example XML snippet showing what I need: 这是显示我需要的示例XML代码段:

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

I need to get the H[number] to be able to compare it with another H[number] . 我需要获取H[number]才能将其与另一个H[number]进行比较。

I'm answering this in Node.js context since you have tagged the question so. 我在Node.js上下文中回答了这个问题,因为您已经标记了问题。

Use fast-xml-parser . 使用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 . 您还可以验证XML等。确保检查自述文件

Here is a way to view them with JS inside of HTML. 这是使用HTML内的JS查看它们的方法。 I had to wrap the H# tags in another tag to make them be valid XML. 我不得不将H#标签包装在另一个标签中,以使其成为有效的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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM