Home Web Front-end JS Tutorial Summary of JS operation XML examples (loading and parsing XML files and strings)_javascript skills

Summary of JS operation XML examples (loading and parsing XML files and strings)_javascript skills

May 16, 2016 pm 03:27 PM

The examples in this article describe how JS operates XML. Share it with everyone for your reference, the details are as follows:

My xml file Login.xml is as follows.

<&#63;xml version="1.0" encoding="utf-8" &#63;>
<Login>
 <Character>
 <C Text="热血" Value="0"></C>
 <C Text="弱气" Value="1"></C>
 <C Text="激情" Value="2"></C>
 <C Text="冷静" Value="3"></C>
 <C Text="冷酷" Value="4"></C>
 </Character>
 <Weapon>
 <W Text="光束剑" Value="0"></W>
 <W Text="光束配刀" Value="1"></W>
 </Weapon>
 <EconomyProperty>
 <P Text="平均型" Value="0"></P>
 <P Text="重视攻击" Value="1"></P>
 <P Text="重视敏捷" Value="2"></P>
 <P Text="重视防御" Value="3"></P>
 <P Text="重视命中" Value="4"></P>
 </EconomyProperty>
</Login>

Copy after login

Now I need to operate on the content of this xml file.

First, we need to load this xml file. Loading the xml file in js is done through XMLDOM.

// 加载xml文档
loadXML = function(xmlFile)
{
 var xmlDoc;
 if(window.ActiveXObject)
 {
 xmlDoc = new ActiveXObject('Microsoft.XMLDOM');
 xmlDoc.async = false;
 xmlDoc.load(xmlFile);
 }
 else if (document.implementation&&document.implementation.createDocument)
 {
 xmlDoc = document.implementation.createDocument('', '', null);
 xmlDoc.load(xmlFile);
 }
 else
 {
 return null;
 }
 return xmlDoc;
}

Copy after login

The xml file object comes out, and I will operate on this document next.

For example, if we now need to get the attributes of the first node of the node Login/Weapon/W, then we can proceed as follows.

// 首先对xml对象进行判断
checkXMLDocObj = function(xmlFile)
{
 var xmlDoc = loadXML(xmlFile);
 if(xmlDoc==null)
 {
 alert('您的浏览器不支持xml文件读取,于是本页面禁止您的操作,推荐使用IE5.0以上可以解决此问题!');
 window.location.href='/Index.aspx';
 }
 return xmlDoc;
}
// 然后开始获取需要的Login/Weapon/W的第一个节点的属性值
var xmlDoc = checkXMLDocObj('/EBS/XML/Login.xml');
var v = xmlDoc.getElementsByTagName('Login/Weapon/W')[0].childNodes.getAttribute('Text')

Copy after login

The way I write in my program is like this. Of course, the way I write in the program has been applied in practice. It is also given for viewing

initializeSelect = function(oid, xPath)
{
 var xmlDoc = checkXMLDocObj('/EBS/XML/Login.xml');
 var n;
 var l;
 var e = $(oid);
 if(e!=null)
 {
 n = xmlDoc.getElementsByTagName(xPath)[0].childNodes;
 l = n.length;
 for(var i=0; i<l; i++)
 {
  var option = document.createElement('option');
  option.value = n[i].getAttribute('Value');
  option.innerHTML = n[i].getAttribute('Text');
  e.appendChild(option);
 }
 }
}

Copy after login

In the above access code, we use xmlDoc.getElementsByTagName(xPath).
It can also be accessed through xmlDoc.documentElement.childNodes(1)..childNodes(0).getAttribute('Text').

Some common methods:

xmlDoc.documentElement.childNodes(0).nodeName, you can get the name of this node.
xmlDoc.documentElement.childNodes(0).nodeValue, you can get the value of this node. This value comes from the xml format like this: b, so you can get the value of b.
xmlDoc.documentElement.childNodes(0).hasChild, you can determine whether there are child nodes
According to my experience, it is best to use the getElementsByTagName(xPath) method to access the node, because this way the node can be located directly through xPath, which will have better performance .

Supplement:

JS parsing XML file

<script type='text/javascript'>
 loadXML = function(xmlFile){
 var xmlDoc=null;
 //判断浏览器的类型
 //支持IE浏览器
 if(!window.DOMParser && window.ActiveXObject){
  var xmlDomVersions = ['MSXML.2.DOMDocument.6.0','MSXML.2.DOMDocument.3.0','Microsoft.XMLDOM'];
  for(var i=0;i<xmlDomVersions.length;i++){
  try{
   xmlDoc = new ActiveXObject(xmlDomVersions[i]);
   break;
  }catch(e){
  }
  }
 }
 //支持Mozilla浏览器
 else if(document.implementation && document.implementation.createDocument){
  try{
  /* document.implementation.createDocument('','',null); 方法的三个参数说明
   * 第一个参数是包含文档所使用的命名空间URI的字符串; 
   * 第二个参数是包含文档根元素名称的字符串; 
   * 第三个参数是要创建的文档类型(也称为doctype)
   */
  xmlDoc = document.implementation.createDocument('','',null);
  }catch(e){
  }
 }
 else{
  return null;
 }
 if(xmlDoc!=null){
  xmlDoc.async = false;
  xmlDoc.load(xmlFile);
 }
 return xmlDoc;
 }
</script>

Copy after login

JS parsing XML string

<script type='text/javascript'>
 loadXML = function(xmlString){
 var xmlDoc=null;
 //判断浏览器的类型
 //支持IE浏览器 
 if(!window.DOMParser && window.ActiveXObject){ //window.DOMParser 判断是否是非ie浏览器
  var xmlDomVersions = ['MSXML.2.DOMDocument.6.0','MSXML.2.DOMDocument.3.0','Microsoft.XMLDOM'];
  for(var i=0;i<xmlDomVersions.length;i++){
  try{
   xmlDoc = new ActiveXObject(xmlDomVersions[i]);
   xmlDoc.async = false;
   xmlDoc.loadXML(xmlString); //loadXML方法载入xml字符串
   break;
  }catch(e){
  }
  }
 }
 //支持Mozilla浏览器
 else if(window.DOMParser && document.implementation && document.implementation.createDocument){
  try{
  /* DOMParser 对象解析 XML 文本并返回一个 XML Document 对象。
   * 要使用 DOMParser,使用不带参数的构造函数来实例化它,然后调用其 parseFromString() 方法
   * parseFromString(text, contentType) 参数text:要解析的 XML 标记 参数contentType文本的内容类型
   * 可能是 "text/xml" 、"application/xml" 或 "application/xhtml+xml" 中的一个。注意,不支持 "text/html"。
   */
  domParser = new DOMParser();
  xmlDoc = domParser.parseFromString(xmlString, 'text/xml');
  }catch(e){
  }
 }
 else{
  return null;
 }
 return xmlDoc;
 }
</script>

Copy after login

Test XML

<&#63;xml version="1.0" encoding="utf-8" &#63;>
<DongFang>
 <Company>
 <cNname>1</cNname>
 <cIP>1</cIP>
 </Company>
 <Company>
 <cNname>2</cNname>
 <cIP>2</cIP>
 </Company> 
 <Company>
 <cNname>3</cNname>
 <cIP>3</cIP>
 </Company>
 <Company>
 <cNname>4</cNname>
 <cIP>4</cIP>
 </Company>
 <Company>
 <cNname>5</cNname>
 <cIP>5</cIP>
 </Company>
 <Company>
 <cNname>6</cNname>
 <cIP>6</cIP>
 </Company>
</DongFang>

Copy after login

Usage:

var xmldoc=loadXML(text.xml)
var elements = xmlDoc.getElementsByTagName("Company");
for (var i = 0; i < elements.length; i++) {
 var name = elements[i].getElementsByTagName("cNname")[0].firstChild.nodeValue;
 var ip = elements[i].getElementsByTagName("cIP")[0].firstChild.nodeValue;
}

Copy after login

I hope this article will be helpful to everyone in JavaScript programming.

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How do I create and publish my own JavaScript libraries? How do I create and publish my own JavaScript libraries? Mar 18, 2025 pm 03:12 PM

Article discusses creating, publishing, and maintaining JavaScript libraries, focusing on planning, development, testing, documentation, and promotion strategies.

How do I optimize JavaScript code for performance in the browser? How do I optimize JavaScript code for performance in the browser? Mar 18, 2025 pm 03:14 PM

The article discusses strategies for optimizing JavaScript performance in browsers, focusing on reducing execution time and minimizing impact on page load speed.

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

How do I debug JavaScript code effectively using browser developer tools? How do I debug JavaScript code effectively using browser developer tools? Mar 18, 2025 pm 03:16 PM

The article discusses effective JavaScript debugging using browser developer tools, focusing on setting breakpoints, using the console, and analyzing performance.

How do I use source maps to debug minified JavaScript code? How do I use source maps to debug minified JavaScript code? Mar 18, 2025 pm 03:17 PM

The article explains how to use source maps to debug minified JavaScript by mapping it back to the original code. It discusses enabling source maps, setting breakpoints, and using tools like Chrome DevTools and Webpack.

How do I use Java's collections framework effectively? How do I use Java's collections framework effectively? Mar 13, 2025 pm 12:28 PM

This article explores effective use of Java's Collections Framework. It emphasizes choosing appropriate collections (List, Set, Map, Queue) based on data structure, performance needs, and thread safety. Optimizing collection usage through efficient

TypeScript for Beginners, Part 2: Basic Data Types TypeScript for Beginners, Part 2: Basic Data Types Mar 19, 2025 am 09:10 AM

Once you have mastered the entry-level TypeScript tutorial, you should be able to write your own code in an IDE that supports TypeScript and compile it into JavaScript. This tutorial will dive into various data types in TypeScript. JavaScript has seven data types: Null, Undefined, Boolean, Number, String, Symbol (introduced by ES6) and Object. TypeScript defines more types on this basis, and this tutorial will cover all of them in detail. Null data type Like JavaScript, null in TypeScript

Getting Started With Chart.js: Pie, Doughnut, and Bubble Charts Getting Started With Chart.js: Pie, Doughnut, and Bubble Charts Mar 15, 2025 am 09:19 AM

This tutorial will explain how to create pie, ring, and bubble charts using Chart.js. Previously, we have learned four chart types of Chart.js: line chart and bar chart (tutorial 2), as well as radar chart and polar region chart (tutorial 3). Create pie and ring charts Pie charts and ring charts are ideal for showing the proportions of a whole that is divided into different parts. For example, a pie chart can be used to show the percentage of male lions, female lions and young lions in a safari, or the percentage of votes that different candidates receive in the election. Pie charts are only suitable for comparing single parameters or datasets. It should be noted that the pie chart cannot draw entities with zero value because the angle of the fan in the pie chart depends on the numerical size of the data point. This means any entity with zero proportion

See all articles