


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.
<?xml version="1.0" encoding="utf-8" ?> <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>
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; }
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')
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); } } }
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>
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>
Test XML
<?xml version="1.0" encoding="utf-8" ?> <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>
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; }
I hope this article will be helpful to everyone in JavaScript programming.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

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.

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.

Python is more suitable for data science and machine learning, while JavaScript is more suitable for front-end and full-stack development. 1. Python is known for its concise syntax and rich library ecosystem, and is suitable for data analysis and web development. 2. JavaScript is the core of front-end development. Node.js supports server-side programming and is suitable for full-stack development.

JavaScript does not require installation because it is already built into modern browsers. You just need a text editor and a browser to get started. 1) In the browser environment, run it by embedding the HTML file through tags. 2) In the Node.js environment, after downloading and installing Node.js, run the JavaScript file through the command line.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Chinese version
Chinese version, very easy to use

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function