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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

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)

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...

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

Is JavaScript hard to learn? Is JavaScript hard to learn? Apr 03, 2025 am 12:20 AM

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

The Evolution of JavaScript: Current Trends and Future Prospects The Evolution of JavaScript: Current Trends and Future Prospects Apr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

The difference in console.log output result: Why are the two calls different? The difference in console.log output result: Why are the two calls different? Apr 04, 2025 pm 05:12 PM

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

See all articles