search

XML Programming-DOM

Feb 20, 2017 pm 03:08 PM

XMLProgramming-DOM

#XML

Parsing technology


##saxAnalysis. dom(Document Object Model, That is, the document object model

)isW3CThe organization's recommended way of processing XML. sax(Simple API for XML) is not an official standard, but it is

XMLThe de facto standard in the community, almost all XML parsers support it. JaxpIntroduction

Jaxp (Java API for XML Processing)

is

JavaA development package for programming

XML, which consists of javax.xml, org. It consists of w3c.dom , org.xml.sax packages and their sub-packages. In the javax.xml.parsers package, several factory classes are defined. When programmers call these factory classes, they can get the The

DOM or SAX parser object used to parse the xml document. DOMBasic overview

DOM(Document Object ModelDocument Object Model

)

, yes W3C

The organization's recommended standard programming interface for handling extensible markup language. XML DOM defines the objects and attributes of all XML elements, as well as the methods (interfaces) to access them. Schematic


#DOM

Model

(document object model)

DOMWhen the parser parses the XML

document, it will parse all the elements in the document into individual elements according to the hierarchical relationship in which they appear.

Node

Object(Node). In dom, the relationship between nodes is as follows: 1

,

are located on one node The node is the parent node of the node (parent)2

,

The node under a node is the child node of the node (children

3, Nodes at the same level and with the same parent node are sibling nodes (sibling)

4,The node set at the next level of a node is the node descendant(descendant)

5,parent,grandfather node and all nodes located above the node are Node’s ancestor(ancestor)

NodeObject

The Node object provides a series of constants to represent The type of node. When developers obtain a certain Node type, they can convert the Node node into the corresponding node object. (Node's subclass object), in order to call its unique method. (See API documentation)

The Node object provides corresponding methods to obtain its parent node or child node. Through these methods, programmers can read the contents of the entire XML document, or add, modify, or delete the contents of the XML document. .

PS: Its sub-interface Element has more functions.

Get the DOM parser# in Jaxp

##1

, call the DocumentBuilderFactory.newInstance() method to create the DOM parser factory.

2

, call the DocumentBuilderFactory object’s newDocumentBuilder() method to get DOMParser object,It is the object of DocumentBuilder.

3

, call the DocumentBuilder object’s parse() method parsing XMLDocument, get the Document object representing the entire document.

4

, through Document objects and some related classes and methods, to XML Document to operate.

Update

XMLDocumentation

javax.xml.transform

in the package The Transformer class is used to convert the Document object representing the XML file into a certain format. For output, for example, apply a style sheet to the xml file and convert it into a html document. Using this object, of course, you can also rewrite the Document object into a XML file.

The Transformer class completes the transformation operation through the transform method, which receives a source and a destination. We can associate the

document

object to be converted through: javax.xml.transform.dom.DOMSource class,

Use javax.xml.transform.stream.StreamResult object to represent the destination of the data.

The Transformer object is obtained through TransformerFactory.

Case:

XML5.xml

<?xml version="1.0" encoding="UTF-8" standalone="no"?><班级 班次="1班" 编号="C1">
	<学生 地址="湖南" 学号="n1" 性别="男" 授课方式="面授" 朋友="n2" 班级编号="C1">
		<名字>张三</名字>
		<年龄>20</年龄>
		<介绍>不错</介绍>
	</学生>
	<学生 学号="n2" 性别="女" 授课方式="面授" 朋友="n1 n3" 班级编号="C1">
		<名字>李四</名字>
		<年龄>18</年龄>

		<介绍>很好</介绍>
	</学生>
	<学生 学号="n3" 性别="男" 授课方式="面授" 朋友="n2" 班级编号="C1">
		<名字>王五</名字>
		<年龄>22</年龄>
		<介绍>非常好</介绍>
	</学生>
	<学生 性别="男">
		<名字>小明</名字>
		<年龄>30</年龄>
		<介绍>好</介绍>
	</学生>
</班级>


package com.pc;

import java.awt.List;
import java.util.ArrayList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 * 
 * @author Switch
 * @function Java解析XML
 * 
 */
public class XML5 {
	// 使用dom技术对xml文件进行操作
	public static void main(String[] args) throws Exception {
		// 1.创建一个DocumentBuilderFactory对象
		DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory
				.newInstance();
		// 2.通过DocumentBuilderFactory,得到一个DocumentBuilder对象
		DocumentBuilder documentBuilder = documentBuilderFactory
				.newDocumentBuilder();
		// 3.指定解析哪个xml文件
		Document document = documentBuilder.parse("src/com/pc/XML5.xml");
		// 4.对XML文档操作
		// System.out.println(document);
		// list(document);
		// read(document);
		// add(document);
		// delete(document, "小明");
		update(document, "小明", "30");
	}

	// 更新一个元素(通过名字更新一个学生的年龄)
	public static void update(Document doc, String name, String age)
			throws Exception {
		NodeList nodes = doc.getElementsByTagName("名字");
		for (int i = 0; i < nodes.getLength(); i++) {
			Element nameE = (Element) nodes.item(i);
			if (nameE.getTextContent().equals(name)) {
				Node prNode = nameE.getParentNode();
				NodeList stuAttributes = prNode.getChildNodes();
				for (int j = 0; j < stuAttributes.getLength(); j++) {
					Node stuAttribute = stuAttributes.item(j);
					if (stuAttribute.getNodeName().equals("年龄")) {
						stuAttribute.setTextContent(age);
					}
				}
			}
		}
		updateToXML(doc);
	}

	// 删除一个元素(通过名字删除一个学生)
	public static void delete(Document doc, String name) throws Exception {
		// 找到第一个学生
		NodeList nodes = doc.getElementsByTagName("名字");
		for (int i = 0; i < nodes.getLength(); i++) {
			Node node = nodes.item(i);
			if (node.getTextContent().equals(name)) {
				Node prNode = node.getParentNode();
				prNode.getParentNode().removeChild(prNode);
			}
		}

		// 更新到XML
		updateToXML(doc);
	}

	// 添加一个学生到XML文件
	public static void add(Document doc) throws Exception {
		// 创建一个新的学生节点
		Element newStu = doc.createElement("学生");
		newStu.setAttribute("性别", "男");
		Element newStu_name = doc.createElement("名字");
		newStu_name.setTextContent("小明");
		Element newStu_age = doc.createElement("年龄");
		newStu_age.setTextContent("21");
		Element newStu_intro = doc.createElement("介绍");
		newStu_intro.setTextContent("好");
		newStu.appendChild(newStu_name);
		newStu.appendChild(newStu_age);
		newStu.appendChild(newStu_intro);
		// 把新的学生节点添加到根元素
		doc.getDocumentElement().appendChild(newStu);

		// 更新到XML
		updateToXML(doc);

	}

	// 更新到XML
	private static void updateToXML(Document doc)
			throws TransformerFactoryConfigurationError,
			TransformerConfigurationException, TransformerException {
		// 得到TransformerFactory对象
		TransformerFactory transformerFactory = TransformerFactory
				.newInstance();
		// 通过TransformerFactory对象得到一个转换器
		Transformer transformer = transformerFactory.newTransformer();
		transformer.transform(new DOMSource(doc), new StreamResult(
				"src/com/pc/XML5.xml"));
	}

	// 具体查询某个学生的信息(小时第一个学生的所有)
	public static void read(Document doc) {
		NodeList nodes = doc.getElementsByTagName("学生");
		// 取出第一个学生
		Element stu1 = (Element) nodes.item(0);
		Element name = (Element) stu1.getElementsByTagName("名字").item(0);
		System.out.println("姓名:" + name.getTextContent() + " 性别:"
				+ stu1.getAttribute("性别"));
	}

	// 遍历该XML文件
	public static void list(Node node) {
		if (node.getNodeType() == node.ELEMENT_NODE) {
			System.out.println("名字:" + node.getNodeName());
		}
		// 取出node的子节点
		NodeList nodes = node.getChildNodes();
		for (int i = 0; i < nodes.getLength(); i++) {
			// 显示所有子节点
			Node n = nodes.item(i);
			list(n);
		}
	}

}

The above is the content of XML programming-DOM. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!


Statement
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
RSS in XML: Unveiling the Core of Content SyndicationRSS in XML: Unveiling the Core of Content SyndicationApr 22, 2025 am 12:08 AM

The implementation of RSS in XML is to organize content through a structured XML format. 1) RSS uses XML as the data exchange format, including elements such as channel information and project list. 2) When generating RSS files, content must be organized according to specifications and published to the server for subscription. 3) RSS files can be subscribed through a reader or plug-in to automatically update the content.

Beyond the Basics: Advanced RSS Document FeaturesBeyond the Basics: Advanced RSS Document FeaturesApr 21, 2025 am 12:03 AM

Advanced features of RSS include content namespaces, extension modules, and conditional subscriptions. 1) Content namespace extends RSS functionality, 2) Extended modules such as DublinCore or iTunes to add metadata, 3) Conditional subscription filters entries based on specific conditions. These functions are implemented by adding XML elements and attributes to improve information acquisition efficiency.

The XML Backbone: How RSS Feeds are StructuredThe XML Backbone: How RSS Feeds are StructuredApr 20, 2025 am 12:02 AM

RSSfeedsuseXMLtostructurecontentupdates.1)XMLprovidesahierarchicalstructurefordata.2)Theelementdefinesthefeed'sidentityandcontainselements.3)elementsrepresentindividualcontentpieces.4)RSSisextensible,allowingcustomelements.5)Bestpracticesincludeusing

RSS & XML: Understanding the Dynamic Duo of Web ContentRSS & XML: Understanding the Dynamic Duo of Web ContentApr 19, 2025 am 12:03 AM

RSS and XML are tools for web content management. RSS is used to publish and subscribe to content, and XML is used to store and transfer data. They work with content publishing, subscriptions, and update push. Examples of usage include RSS publishing blog posts and XML storing book information.

RSS Documents: The Foundation of Web SyndicationRSS Documents: The Foundation of Web SyndicationApr 18, 2025 am 12:04 AM

RSS documents are XML-based structured files used to publish and subscribe to frequently updated content. Its main functions include: 1) automated content updates, 2) content aggregation, and 3) improving browsing efficiency. Through RSSfeed, users can subscribe and get the latest information from different sources in a timely manner.

Decoding RSS: The XML Structure of Content FeedsDecoding RSS: The XML Structure of Content FeedsApr 17, 2025 am 12:09 AM

The XML structure of RSS includes: 1. XML declaration and RSS version, 2. Channel (Channel), 3. Item. These parts form the basis of RSS files, allowing users to obtain and process content information by parsing XML data.

How to Parse and Utilize XML-Based RSS FeedsHow to Parse and Utilize XML-Based RSS FeedsApr 16, 2025 am 12:05 AM

RSSfeedsuseXMLtosyndicatecontent;parsingtheminvolvesloadingXML,navigatingitsstructure,andextractingdata.Applicationsincludebuildingnewsaggregatorsandtrackingpodcastepisodes.

RSS Documents: How They Deliver Your Favorite ContentRSS Documents: How They Deliver Your Favorite ContentApr 15, 2025 am 12:01 AM

RSS documents work by publishing content updates through XML files, and users subscribe and receive notifications through RSS readers. 1. Content publisher creates and updates RSS documents. 2. The RSS reader regularly accesses and parses XML files. 3. Users browse and read updated content. Example of usage: Subscribe to TechCrunch's RSS feed, just copy the link to the RSS reader.

See all articles

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

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

DVWA

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

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Atom editor mac version download

Atom editor mac version download

The most popular open source editor