当前位置:网站首页>DOM parsing of XML file case code sentence by sentence analysis
DOM parsing of XML file case code sentence by sentence analysis
2022-06-28 06:58:00 【Xiaobinbin &】
One 、 What is? xml
xml Is extensible markup language , Mainly used for transmission 、 Store the data , Instead of showing the data .xml When you file W3C The data transmission format recommended by the organization .
Two 、xml What is the file format
xml The documents are mainly made up of xml Statement 、 label 、 Root element and element composition .
xml Statement :
<?xml version="1.0" encoding="UIF-8" ?>
version : Version number , Need to meet XML1.0 Format
encoding: Character encoding , The default is “UTF-8”label
<name> " Zhang San " </name> This is a pair of labels
<name> The start tag ;</name> End tag ; " Zhang San " Text content
Root element
<people></people> This is a pair of root elements , One xml There is only one root element in the file , The other elements are in this root element
Elements
<name> " Zhang San " </name> This is an element , Element is composed of child elements and character data
Naming rules for elements :1、 The name can contain letters 、 Numbers or other characters
2、 Names cannot begin with numbers or punctuation
3、 The name cannot be in characters xml( perhaps XML,Xml) Start
4、 The name cannot contain spaces
3、 ... and 、xml File content cases
<?xml version="1.0" encoding="GB2312"?>
<PhoneInfo>
<Brand name=" Huawei ">
<Type>Mate30</Type>
<Type>Hova20</Type>
<Type>p30</Type>
</Brand>
<Brand name=" Apple ">
<Type>iphone11Pro</Type>
<Type>iphone12p</Type>
</Brand>
</PhoneInfo>Four 、DOM analysis xml file
DOM Based on XML Tree structure to complete the parsing .DOM analysis xml When documenting , According to the read document , Create a tree structure stored in memory , And then through DOM The interface class operates on the tree structure ; For multiple visits xml file , Compare the consumption of resources .
DOM It can be done to xml Read from the memory of the document , Modify and store . Collective realization , This program is explained sentence by sentence .
package cn.kgc;
import org.w3c.dom.*;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
//@Author
//@Date
//@Description demonstration DOM analysis xml file
public class TestDome {
Document document;
public static void main(String[] args) {
TestDome d = new TestDome();
try {
d.getDocument("resources\\ Collection information .xml");
// One 、 Read property values
d.getBrands("Type","name");
// Two 、 Read text value
d.getChildren("Brand");
// 3、 ... and 、 Store data and assign values
d.saveXML("src\\cn\\kgc\\poeple.xml");
// Modifying data
//1、 Delete
d.changeDele();
d.saveXML("src\\cn\\kgc\\poeple.xml");
//2、 Modify properties
d.changeName();
d.saveXML("src\\cn\\kgc\\poeple.xml");
//3、 add to
d.changeAddElement();
d.saveXML("src\\cn\\kgc\\poeple.xml");
} catch (Exception e) {
e.printStackTrace();
}
}
// establish Document Instance object , obtain xml Document DOM Count , That is, get the root node
public void getDocument(String xmlPath) throws Exception {
// establish DOM Factory instance object
// DocumentBuilderFactory Abstract class , No instantiated object
// Method : static DocumentBuilderFactory newInstance() Get a new instance DocumentBuilderFactory .
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
// from DOM The instance factory obtains DOM Parser
// Method : abstract DocumentBuilder newDocumentBuilder() Create a new... Using the currently configured parameters DocumentBuilder example .
DocumentBuilder buider = factory.newDocumentBuilder();
// adopt DOM Parser parsing XML file , Get one Document object , That is to get DOM Trees
// Method : Document parse(File f) Parse the contents of a given file into XML file , And return to a new DOM Document object .
document = buider.parse(new FileInputStream(xmlPath));
}
// Get the value of the property
public void getBrands(String tagName , String attName) {// Print all brand names
// Get all tagName List of nodes
// Method : NodeList getElementsByTagName(String tagname) Return in document order NodeList Of Elements , With the given tag name , And included in the documentation
// It means NodeList Represents a set , Read out the child nodes under the root node , Put it in the collection
NodeList breads = document.getElementsByTagName(tagName);
for (int i = 0; i < breads.getLength(); i++) {
// Get the label of each element
// Traverse all the child nodes in the collection
// Method : Node item(int index) Returns... In the collection index term .
Node brand = breads.item(i);
// In principle, the label is Element Elements
// public interface Element extends Node Element Inherited Node Parent class , namely Node It can be transformed into Element
// What the child node element here needs is Element type , That is, it needs to be transformed
Element e = (Element) brand;
// Get the attribute value according to the attribute
// Method : String getAttribute(String name) Retrieve attribute values by name .
String name = e.getAttribute(attName);
System.out.println(name);
}
}
// Interaction between parent and child nodes , Display the text under the child node
public void getChildren(String tagName) {
// Get all child nodes under the root node
NodeList breads = document.getElementsByTagName(tagName);
// Traverse each child node
for (int i = 0; i < breads.getLength(); i++) {
// Get the label of each node
Node node = breads.item(i);
Element e = (Element) node;
String name = e.getAttribute("name");
System.out.println(name);
// Take all text nodes of each child node
// Method : NodeList getChildNodes() A NodeList Contains all child nodes of this node .
NodeList children = node.getChildNodes();
for (int j = 0; j < children.getLength(); j++) {
// Each text node
// Method : Node item(int index) Returns... In the collection index term .
Node child = children.item(j);
// if (child instanceof Element) {// Exclude empty line markers
// // Convert a text node into a text file
if (child instanceof Element) {
Text text = (Text) child.getFirstChild();
// Output content
System.out.println(text.getWholeText());
}
}
}
}
// Storage XML data
public void saveXML(String path) throws Exception {
// Create a storage factory
TransformerFactory factory = TransformerFactory.newInstance();
// Create a storage factory object
Transformer trans = factory.newTransformer();
// Format adjustment
trans.setOutputProperty(OutputKeys.INDENT , "yes");
trans.setOutputProperty("{http://xml.apache.org/xslt}indent-amount" , "4");
// establish DOMSource object , contain xml Information
DOMSource source = new DOMSource(document);
// FileOutputStream fos = new FileOutputStream(path);
// OutputStreamWriter osw =new OutputStreamWriter(fos,"GB2312");
// Create a file input result stream object
StreamResult result = new StreamResult(new OutputStreamWriter(new FileOutputStream(path) , "GB2312"));
// take DOMSource Object xml Information stored in people.xml in
trans.transform(source , result);
}
// Modify the text
public void changeDele() {
//1、 Delete
Node root = document.getElementsByTagName("PhoneInfo").item(0);
Node iphone = document.getElementsByTagName("Brand").item(1);
// Method :Node removeChild(Node oldChild) Remove... From the sub list oldChild Indicated child nodes , And back to .
root.removeChild(iphone);
}
public void changeName() {
// 2、 Change the apple attribute to iphone, At the same time, the sub text iphone12p Change it to iphone100
Node iPhone = document.getElementsByTagName("Brand").item(0);
Element e = (Element) iPhone;
// Modify the apple attribute name “ Apple ” by “iphone”,
e.setAttribute("name" , "iphone");
// Method : NodeList getChildNodes() A NodeList Contains all child nodes of this node .
NodeList nodes = e.getChildNodes();
for (int i = 0; i < nodes.getLength(); i++) {
Node node = nodes.item(i);
//instanceof To exclude empty elements, an error is reported
// node instanceof Element node A variable is Element type , It is true, Conversely false
if (node instanceof Element) {
Text text = (Text) node.getFirstChild();
// Judge whether the text is "iphone12p", If yes, change to "iphone100" And exit
// Method :String getWholeText() All the text of a logically adjacent text node Text Return to this node , Connect in document order .
if (text.getWholeText().equals("iphone12p")) {
text.setData("iphone100");
return;
}
}
}
}
public void changeAddElement() {
//3、 Add Samsung brand , Increase type Galay10.20
Node root = document.getElementsByTagName("PhoneInfo").item(0);
// Node iPhone = document.getElementsByTagName("Brand").item(1);
// Create a new child node
Element brand = document.createElement("Brand");
// Set the attribute of the child node to name=“ samsung ”
brand.setAttribute("name"," samsung " );
// Create the element to be added under the child node
Element type1 = document.createElement("Type");
Element type2 = document.createElement("Type");
// What is the text content of each element
Text t1 = document.createTextNode("Galaxy10");
Text t2 = document.createTextNode("Galaxy20");
// The nodes newChild Add to the end of this node's list of child nodes .
// Node appendChild(Node newChild) The nodes newChild Add to the end of this node's list of child nodes .
type1.appendChild(t1);
type2.appendChild(t2);
brand.appendChild(type1);
brand.appendChild(type2);
root.appendChild(document.createTextNode("\n"));
root.appendChild(brand);
}
}
边栏推荐
- Error reporting - resolve core JS / modules / es error. cause. JS error
- 服务器正文18:UDP可靠传输的理解和思考(读云凤博客有感)
- Students who do not understand the code can also send their own token. The current universal dividend model can be divided into BSC and any generation B
- Recommend several 0 code, free, learning and using visualization tools
- Puge -- understanding of getordefault() method
- 职场IT老鸟的几点小习惯
- 普歌 -- getOrDefault()方法理解
- BACnet/IP網關如何采集樓宇集中控制系統數據
- Is it safe to open a stock trading account on your mobile phone?
- RN7302三相电量检测(基于STM32单片机)
猜你喜欢

Interpretation of Blog

代码没写错,渲染页面不显示原因

eyebeam高级设置

Exception handling (I) -- null pointer and array index out of bounds

Comprehensive analysis of real enterprise software testing process

Libuv framework echo server C source code explanation (TCP part)

Pytorch RNN learning notes

Rn7302 three-phase electric quantity detection (based on STM32 single chip microcomputer)

js正则表达式系统讲解(全面的总结)

Reinforcement learning - grid world
随机推荐
未来互联网人才还稀缺吗?哪些技术方向热门?
普歌--三大基础排序,冒泡·选择·快速
JS of learning notes -- split(), replace(), join()
职场IT老鸟的几点小习惯
CMAKE小知识
Yolov5 adds a small target detection layer
FPGA - 7系列 FPGA SelectIO -09- 高级逻辑资源之IO_FIFO
BACnet/IP网关如何采集楼宇集中控制系统数据
自律挑战30天
Linked list (I) - remove linked list elements
extern “C“概述
[rust daily] published on rust 1.43.0 on April 23, 2020
AttributeError: 'callable_iterator' object has no attribute 'next'
Wechat applets - basics takes you to understand the life cycle of applets (I)
Libuv framework echo server C source code explanation (TCP part)
调接口事件API常用事件方法
代码没写错,渲染页面不显示原因
Voice network VQA: make the user's subjective experience of unknown video quality in real-time interaction known
fpm工具安装
Build your jmeter+jenkins+ant