DOM解析的基本思路:
1、将整个XML文件一次性读入内存
2、将整个XML看做一棵树
3、XML中的每一个标签,属性,文本都看做是树上的一个结点
4、然后可以对结点进行增删改查的操作
话不多说,上代码。
1、首先我在D:\ABC中新建了一个文本文件,重命名为stus.xml,以下是文件中的内容
<?xml version = "1.0" encoding = "GBK" ?> <stus class = "S160401A"> <stu num = "001" > <name>张三</name> <age>20</age> <sex>男</sex> </stu> <stu num = "002"> <name>李四</name> <age>21</age> <sex>女</sex> </stu> <stu num = "003"> <name>王五</name> <age>22</age> <sex>男</sex> </stu> </stus>
在第一行是XML声明,version表示版本号,encoding表示编码方式,微软的记事本用的是国标的编码方式,如果要用UTF-8,则要在另存为窗口中修改编码方式为UTF-8。
必须且只能有一对根标签,我写的根标签是
2、这是一个学生类,定义了一些属性和get、set方法
<span style="font-size: 16px;">public class Student { public static String Class; private String name; private int num; private int age; private char sex; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getNum() { return num; } public void setNum(int num) { this.num = num; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public char getSex() { return sex; } public void setSex(char sex) { this.sex = sex; } }</span>
3、这是用DOM解析的类,看这个类之前还要了解一下。
DocumentBuilderFactory DOM解析器工厂
DocumentBuilder DOM解析器
Document 文档对象
Node 结点【接口】
Element 元素结点【标签结点】
Attr 属性结点
Text 文本结点
Node 是Document,Element,Attr,Text的父接口
NodeList 结点列表
NamedNodeMap 一个结点的所有属性
<span style="font-size: 16px;">import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Attr; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import bean.Student; public class DOMParser { public static void main(String[] args) throws Exception { // 得到解析器工厂对象 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); // 生产一个解析器对象 DocumentBuilder builder = factory.newDocumentBuilder(); // 开始解析XML文件,得到解析的结果,是一个Document对象 // Document对象叫做文档树对象 Document dom = builder.parse("D:\\ABC\\stus.xml"); // 通过Document对象提取数据 // Document对象的第一个子节点是根节点[根标签] Node root = dom.getFirstChild(); // 获得标签的名字 String str = root.getNodeName(); // 获得根节点的属性 NamedNodeMap attrs = root.getAttributes(); // 强转成Attr类型 属性类 Attr attr = (Attr) attrs.getNamedItem("class"); // 获得属性里的值 String v = attr.getValue(); System.out.println(v); // 获得所有的学生------------------------------------- NodeList list = root.getChildNodes(); for (int i = 0; i < list.getLength(); i++) { Node node = list.item(i); // 判断是否是标签结点 if (node instanceof Element) { Element e = (Element) node; // 获得标签结点里属性的值 String num = e.getAttribute("num"); System.out.println(num); // 输出标签中的文本 // System.out.println(e.getTextContent()); // 继续获得stu的子节点 NodeList nodeList = e.getChildNodes(); for (int j = 0; j < nodeList.getLength(); j++) { Node n = nodeList.item(j); if (n instanceof Element) { Element ele = (Element) n; // 获得元素结点的标签名字 String nodeName = ele.getNodeName(); // 获得元素结点标签中的文本 String value = ele.getTextContent(); if (nodeName.equals("name")) { System.out.println("姓名:" + value); } else if (nodeName.equals("age")) { System.out.println("年龄:" + value); } else if (nodeName.equals("sex")) { System.out.println("性别:" + value); } } } } } } }</span>
自己在其中总结了一些方法:
DocumentBuilderFactory类:
public static DocumentBuilderFactory newInstance(); //得到解析器工厂对象 public abstract DocumentBuilder newDocumentBuilder(); //生产一个解析器对象
DocumentBuilder类:
public Document parse(String uri); //解析路径为uri的XML文件,得到解析的结果是一个Document对象
Node类:
public Node getFirstChild(); //得到Document对象的第一个子结点,也就是根结点、或者叫根标签,在上面的代码中得到的是stus,看上面的第1点中的XML文件的内容。 public NamedNodeMap getAttributes();//获得结点的属性 public NodeList getChildNodes();//获得所有子结点 public String getNodeName();//获得标签的名字 public String getTextContent() throws DOMException;//获得标签结点中的文本
NamedNodeMap类:
public Node getNamedItem(String name);//返回所有名字为name的结点
Attr类:
public String getValue();//获得属性里的值
NodeList类:
public Node item(int index);//返回第index个结点
Element类:
public String getAttribute(String name);//获得标签结点里属性name的值
The above is the detailed content of Detailed explanation of XML-JAXP technology-DOM parsing. For more information, please follow other related articles on the PHP Chinese website!

JSONFeed is a JSON-based RSS alternative that has its advantages simplicity and ease of use. 1) JSONFeed uses JSON format, which is easy to generate and parse. 2) It supports dynamic generation and is suitable for modern web development. 3) Using JSONFeed can improve content management efficiency and user experience.

How to build, validate and publish RSSfeeds? 1. Build: Use Python scripts to generate RSSfeed, including title, link, description and release date. 2. Verification: Use FeedValidator.org or Python script to check whether RSSfeed complies with RSS2.0 standards. 3. Publish: Upload RSS files to the server, or use Flask to generate and publish RSSfeed dynamically. Through these steps, you can effectively manage and share content.

Methods to ensure the security of XML/RSSfeeds include: 1. Data verification, 2. Encrypted transmission, 3. Access control, 4. Logs and monitoring. These measures protect the integrity and confidentiality of data through network security protocols, data encryption algorithms and access control mechanisms.

XML is a markup language used to store and transfer data, and RSS is an XML-based format used to publish frequently updated content. 1) XML describes data structures through tags and attributes, 2) RSS defines specific tag publishing and subscribed content, 3) XML can be created and parsed using Python's xml.etree.ElementTree module, 4) XML nodes can be queried for XPath expressions, 5) Feedparser library can parse RSSfeed, 6) Common errors include tag mismatch and encoding issues, which can be validated by XMLlint, 7) Processing large XML files with SAX parser can optimize performance.

XML is a markup language for data storage and exchange, and RSS is an XML-based format for publishing updated content. 1. XML defines data structures, suitable for data exchange and storage. 2.RSS is used for content subscription and uses special libraries when parsing. 3. When parsing XML, you can use DOM or SAX. When generating XML and RSS, elements and attributes must be set correctly.

Use Python to convert from XML/RSS to JSON. 1) parse source data, 2) extract fields, 3) convert to JSON, 4) output JSON. Use the xml.etree.ElementTree and feedparser libraries to parse XML/RSS, and use the json library to generate JSON data.

XML/RSS and RESTAPI work together in modern network development by: 1) XML/RSS is used for content publishing and subscribing, and 2) RESTAPI is used for designing and operating network services. Using these two can achieve efficient content management and dynamic updates.

Adding an image path to XML requires the <image> element, whose syntax is <image src="image_path" />, where the src attribute specifies the path to the image file. The path can be a relative or an absolute path, and the image file must be the same directory as the XML file or specify the full path.


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

Atom editor mac version download
The most popular open source editor

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

Zend Studio 13.0.1
Powerful PHP integrated development environment

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.

SublimeText3 Chinese version
Chinese version, very easy to use