XML Programming-DOM
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
(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.
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.
UpdateXMLDocumentation
javax.xml.transformin 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
documentobject 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)!

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

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

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

Hot Topics

Can XML files be opened with PPT? XML, Extensible Markup Language (Extensible Markup Language), is a universal markup language that is widely used in data exchange and data storage. Compared with HTML, XML is more flexible and can define its own tags and data structures, making the storage and exchange of data more convenient and unified. PPT, or PowerPoint, is a software developed by Microsoft for creating presentations. It provides a comprehensive way of

Convert XML data in Python to CSV format XML (ExtensibleMarkupLanguage) is an extensible markup language commonly used for data storage and transmission. CSV (CommaSeparatedValues) is a comma-delimited text file format commonly used for data import and export. When processing data, sometimes it is necessary to convert XML data to CSV format for easy analysis and processing. Python is a powerful

Handling Errors and Exceptions in XML Using Python XML is a commonly used data format used to store and represent structured data. When we use Python to process XML, sometimes we may encounter some errors and exceptions. In this article, I will introduce how to use Python to handle errors and exceptions in XML, and provide some sample code for reference. Use try-except statement to catch XML parsing errors When we use Python to parse XML, sometimes we may encounter some

Python parses special characters and escape sequences in XML XML (eXtensibleMarkupLanguage) is a commonly used data exchange format used to transfer and store data between different systems. When processing XML files, you often encounter situations that contain special characters and escape sequences, which may cause parsing errors or misinterpretation of the data. Therefore, when parsing XML files using Python, we need to understand how to handle these special characters and escape sequences. 1. Special characters and

How to handle XML and JSON data formats in C# development requires specific code examples. In modern software development, XML and JSON are two widely used data formats. XML (Extensible Markup Language) is a markup language used to store and transmit data, while JSON (JavaScript Object Notation) is a lightweight data exchange format. In C# development, we often need to process and operate XML and JSON data. This article will focus on how to use C# to process these two data formats, and attach

Use PHPXML functions to process XML data: Parse XML data: simplexml_load_file() and simplexml_load_string() load XML files or strings. Access XML data: Use the properties and methods of the SimpleXML object to obtain element names, attribute values, and subelements. Modify XML data: add new elements and attributes using the addChild() and addAttribute() methods. Serialized XML data: The asXML() method converts a SimpleXML object into an XML string. Practical example: parse product feed XML, extract product information, transform and store it into a database.

Using Python to implement data validation in XML Introduction: In real life, we often deal with a variety of data, among which XML (Extensible Markup Language) is a commonly used data format. XML has good readability and scalability, and is widely used in various fields, such as data exchange, configuration files, etc. When processing XML data, we often need to verify the data to ensure the integrity and correctness of the data. This article will introduce how to use Python to implement data verification in XML and give the corresponding

Jackson is a Java-based library that is useful for converting Java objects to JSON and JSON to Java objects. JacksonAPI is faster than other APIs, requires less memory area, and is suitable for large objects. We use the writeValueAsString() method of the XmlMapper class to convert the POJO to XML format, and the corresponding POJO instance needs to be passed as a parameter to this method. Syntax publicStringwriteValueAsString(Objectvalue)throwsJsonProcessingExceptionExampleimp
