Home Backend Development XML/RSS Tutorial Detailed explanation of JAXP case of XML parsing

Detailed explanation of JAXP case of XML parsing

Feb 16, 2017 pm 03:37 PM

Based on a CRUD case, a detailed explanation of JAXP xml parsing technology:


First of all, it is known that the data in an xml file is as follows:


1

2

3

4

5

6

7

8

9

10

11

12

13

<?xml version="1.0" encoding="UTF-8" standalone="no"?>

<书架>

    <书 出版社="深圳出版社1"><!-- 出版社="深圳出版社1"属性名和属性值 -->

        <书名>Java</书名>

        <作者>张泽华</作者>

        <售价>39.00元</售价>

    </书>

    <书 出版社="深圳出版社2">

        <书名>JavaScript网页开发</书名>

        <作者>李红蕾</作者>

        <售价>28.00元</售价>

    </书>

</书架>

Copy after login


Then according to the unit test form, CRUD is written in a test framework method. To facilitate testing the correctness of the code.



##

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

163

164

165

166

167

168

169

170

171

172

173

174

175

176

177

178

179

180

181

182

183

184

185

186

187

188

189

190

191

192

193

194

195

196

197

198

199

200

201

202

203

204

205

206

207

208

209

210

211

212

213

214

215

216

217

218

219

220

221

222

223

224

package com.itheima.dom;

 

import java.io.IOException;

 

import javax.xml.parsers.DocumentBuilder;

import javax.xml.parsers.DocumentBuilderFactory;

import javax.xml.parsers.ParserConfigurationException;

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 junit.framework.Assert;

 

import org.junit.Test;

import org.w3c.dom.Document;

import org.w3c.dom.Element;

import org.w3c.dom.Node;

import org.w3c.dom.NodeList;

import org.xml.sax.SAXException;

 

/*

 *

 *          使用 xml  dom 对xml 文件进行 CRUD操作

 *

 1.读取节点的文本内容

 2.读取属性值

 3.添加节点

 4.删除节点

 5.更新节点

 6.打印所有元素节点的名称.

 protected的方法,不让new对象

 

 *

 */

public class TestDomExercises {

 

    // 读取节点的文本内容 : Java就业培训教程

    @Test

    public void testReadContent() throws Exception {// 测试框架异常需要抛出

 

        // 获得代表xml 文件的document 对象

 

        Document document = getDocument();

 

        // 根据标签名 获得 名的标签的 节点 列表

        NodeList nl= document.getElementsByTagName("书名");

 

        int length = nl.getLength();

 

        System.out.println("长度 : " + length);

 

        // 返回第一个 书名 节点

        Node firstBookNameNode = nl.item(0);

 

        String result = firstBookNameNode.getTextContent();//String getTextContent()  此属性返回此节点及其后代的文本内容。

 

        Assert.assertEquals("Java", result);

    }

 

    // 2.读取属性值 : 出版社="深圳出版社1"

    @Test

    public void testReadAttribute() throws Exception {

 

        // 获得document 对象

        Document document = getDocument();

 

        NodeList nl = document.getElementsByTagName("书");

 

        // 拿到 第一本书的 节点 对象

        // Node firstBookNode = nl.item(0);

 

        // 注意:这里查看api 之后, 发现Node里面没有【根据 属性名获得属性值】的方法,而 元素 element 有 直接【根据 属性名获得属性值】的方法, 而这里 拿到的 实际上就是

        // 一个 元素 Node节点, 所以 这里 想到了强制类型 转换 , 转换为 元素Element , 然后 根据他的方法的属性名获得属性的值

 

        // 拿到 第一本书

        //nl.item(0)返回Node对象,向下转型成Element对象。因为Element里面有直接根据元素找值得方法:getAttribute("出版社");根据名称获取属性的值

        Element firstBookElement = (Element) nl.item(0);

 

        //String getAttribute(String name) 通过名称获得属性值。

        String result = firstBookElement.getAttribute("出版社");//根据属性名获取属性值

 

        Assert.assertEquals("深圳出版社1", result);

 

    }

 

    // 3.添加节点 : <售价>79.00元</售价>

    @Test

    public void testAddPrice() throws Exception, SAXException, IOException {

 

        // 获得document 对象

        Document document = getDocument();

 

        // 获得第一本书 节点

        Node firstBookNode = document.getElementsByTagName("书").item(0);

 

        // 创建 售价 节点, 并且将 文本设置为 79.00元

        //Element org.w3c.dom.Document.createElement(String tagName)

        //Element createElement(String tagName) 创建指定类型的元素。

        Element createPriceElement = document.createElement("售价");

        //

        createPriceElement.setTextContent("79.00元");//<售价>79.00元</售价>

 

        //Node org.w3c.dom.Node.appendChild(Node newChild)

        firstBookNode.appendChild(createPriceElement);//将节点 newChild 添加到此节点的子节点列表的末尾。如果 newChild 已经存在于树中,则首先移除它。

 

        writeBack2Xml(document);

 

    }

 

    /*

     * 回去写代码时, 如果碰到这个 异常 :

     *

     * initializationError(org.junit.runner.manipulation.Filter)

     *

     * 就是 你 没有 加 @Test 注解

     */

 

    // 4.删除节点: <售价>39.00元</售价>

    @Test

    public void testDelete() throws Exception, SAXException, IOException {

 

        // 获得 document 对象

        Document document = getDocument();

 

        // 获得 售价 39.00元的 节点

        NodeList priceNodeList = document.getElementsByTagName("售价");

 

        for (int i = 0; i < priceNodeList.getLength(); i++) {

 

            // 拿到 每个售价节点

            Node node = priceNodeList.item(i);

 

            if ("39.00元".equals(node.getTextContent())) {

 

                // 如果进来, 则说明找到 39.00元的售价节点

                // 拿到当前节点的父节点, 然后 删除 这个 节点

                node.getParentNode().removeChild(node);

 

            }

        }

 

        // 更新 到 xml 文件

        writeBack2Xml(document);

 

    }

 

    // 5.更新节点 : <售价>79.00元</售价> ---------->> <售价>9.9元</售价>

    public void testUpdatePrice() {

 

    }

 

    // 6.打印所有元素节点的名称.

 

    @Test

    public void testPrintAllElementsName() throws Exception, SAXException,

            IOException {

 

        // 获得document 对象

        Document document = getDocument();

 

        printAllElementsName(document);

    }

 

    public void printAllElementsName(Node node) {

 

        if (Node.ELEMENT_NODE == node.getNodeType()) {

 

            // 说明 就是 元素 节点

            System.out.println(node.getNodeName());

        }

 

        NodeList childNodes = node.getChildNodes();

 

        for (int i = 0; i < childNodes.getLength(); i++) {

 

            // 拿到 遍历过程中的 每一个 node

            Node item = childNodes.item(i);

 

            printAllElementsName(item);

        }

    }

 

    // 需要将内存中的document 对象 重新写回到 xml 文件中去

    private void writeBack2Xml(Document document)

            throws TransformerFactoryConfigurationError,

            TransformerConfigurationException, TransformerException {

 

        // 如何弄?

        // 查看 文档, transformerFacotry --->> Transformer实例

 

        TransformerFactory factory = TransformerFactory.newInstance();

 

        // 获得转换器的 实例对象

        Transformer transformer = factory.newTransformer();

 

        // 调用 转换方法 将 内存中document 对象 写到 xml 文件中 去

        //abstract  void transform(Source xmlSource, Result outputTarget) 将 XML Source 转换为 Result。

        //DOMSource正好是Source实现类。而且它有构造方法DOMSource(Node n) 正好接收一个Node

        //Result实现类有一个StreamResult他的构造方法StreamResult.StreamResult(String systemId)

// systemId:Must be a String that conforms to the URI syntax

        //因此源Source,和结果Result都解决了

        transformer.transform(new DOMSource(document), new StreamResult(

                "src/book.xml"));

    }

 

    // 抽取 方法 (右键——>>refactor--->>rctract method)--->> 重构 -- 抽取 方法

    private Document getDocument() throws ParserConfigurationException,

            SAXException, IOException {

        // 1. 获得工厂

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

 

        // 2. 获得 builder 对象

        DocumentBuilder builder = factory.newDocumentBuilder();

 

        // 3. 拿到 代表xml 文件的document 对象

        Document document = builder.parse("src/book.xml");

        return document;

    }

 

}

Copy after login
The above is the detailed explanation of the JAXP case of XML parsing. For more related content, please pay attention to the PHP Chinese website (www .php.cn)!



Statement of this Website
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

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Use Gin framework to implement XML and JSON data parsing functions Use Gin framework to implement XML and JSON data parsing functions Jun 22, 2023 pm 03:14 PM

In the field of web development, XML and JSON, one of the data formats, are widely used, and the Gin framework is a lightweight Go language web framework that is simple, easy to use and has efficient performance. This article will introduce how to use the Gin framework to implement XML and JSON data parsing functions. Gin Framework Overview The Gin framework is a web framework based on the Go language, which can be used to build efficient and scalable web applications. The Gin framework is designed to be simple and easy to use. It provides a variety of middleware and plug-ins to make the development

Java Error: XML Parsing Error, How to Fix and Avoid Java Error: XML Parsing Error, How to Fix and Avoid Jun 24, 2023 pm 05:46 PM

As Java becomes more and more widely used in the Internet field, many developers may encounter the problem of "XML parsing error" when using XML for data parsing. XML parsing error means that when using Java to parse XML data, the program cannot parse the data normally due to incorrect data format, unclosed tags, or other reasons, thus causing errors and exceptions. So, how should we solve and avoid when facing XML parsing errors? This article will explain this issue in detail. 1. XML parsing

How to solve the problem of high memory usage of XML parsing in Java development How to solve the problem of high memory usage of XML parsing in Java development Jun 29, 2023 am 09:37 AM

XML is a commonly used data exchange format. In Java development, large-scale XML files often need to be parsed. However, since XML files often contain a large number of nodes and elements, traditional XML parsing methods can easily lead to high memory usage. This article will introduce some methods to solve the problem of high memory usage of XML parsing. Using the SAX parser SAX (SimpleAPI for XML) is an event-driven XML parsing method. Compared to DOM (DocumentO

How to use PHP to parse XML and obtain node content How to use PHP to parse XML and obtain node content Jun 13, 2023 pm 04:31 PM

When developing web applications, XML is a very important data format that can be used in scenarios such as data exchange and information sharing. In PHP, we can use built-in functions and third-party libraries to parse and manipulate XML. Below we will discuss how to use PHP to parse XML and obtain the content of the nodes in it. Parse XML files First, we need to parse XML files. PHP provides two main methods to parse XML: 1.1. Using SimpleXML SimpleXML is within PHP

Solution to solve Java XML parsing exception (XMLParsingException) Solution to solve Java XML parsing exception (XMLParsingException) Aug 19, 2023 pm 01:43 PM

Solution introduction to solving Java XML parsing exceptions (XMLParsingException): When processing XML files, we often encounter XML parsing exceptions (XMLParsingException). This is caused by XML file format errors or incorrect XML parser configuration. This article will introduce some common XML parsing exceptions and solutions to help developers better deal with these problems. 1. The cause of XML parsing exception is parsing XML document.

A guide to XML parsing and generation in PHP A guide to XML parsing and generation in PHP Jun 11, 2023 am 11:01 AM

With the development of the Internet, XML (Extensible Markup Language) has become a popular data exchange format. In PHP, XML parsing and generation are very important skills because PHP is often used to process XML documents. This guide will introduce how to parse and generate XML documents in PHP to help developers better master this skill. 1. XML parsing XML parsing is the process of converting XML documents into data structures in PHP. PHP provides two main XML parsing methods, DOM and SimpleX

PHP8.1 update: enhanced XML parsing capabilities PHP8.1 update: enhanced XML parsing capabilities Jul 07, 2023 am 09:22 AM

PHP8.1 update: Enhanced XML parsing function With the rapid development of the Internet, XML (Extensible Markup Language) plays an important role in data exchange and information transmission. As a universal data format, XML is often used to transfer and store data between different applications. In order to provide better XML parsing capabilities, PHP8.1 has enhanced the XML parsing function to provide developers with more convenience. In PHP8.1, an important improvement is the introduction of libxml_disabl

How to reduce XML parsing memory usage in Java development How to reduce XML parsing memory usage in Java development Jun 30, 2023 pm 09:19 PM

How to solve the problem of XML parsing occupying too much heap memory in Java development Introduction: With the explosive growth of information and data, the importance of XML (Extensible Markup Language) in enterprise application development continues to increase. However, you may encounter problems with excessive heap memory usage during XML parsing, especially when dealing with large XML files. This article will introduce some methods and techniques to solve this problem. 1. Understand the XML parsing process. Before we deeply solve the problem of XML parsing occupying too much heap memory, we first understand the basics of XML parsing.

See all articles