


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.

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.


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

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

Hot Article

Hot Tools

SublimeText3 Chinese version
Chinese version, very easy to use

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 English version
Recommended: Win version, supports code prompts!

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),

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.
