当前位置:网站首页>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);
}
}
边栏推荐
猜你喜欢

浮动与定位

Promotion intégrale et ordre des octets de fin de taille

JS regular expression system explanation (comprehensive summary)
面经---测试工程师web端自动化---大厂面试题

FPGA - 7系列 FPGA SelectIO -07- 高级逻辑资源之ISERDESE2
![[interval DP] stone consolidation](/img/d2/493badf59b63498782ada81be9aa43.jpg)
[interval DP] stone consolidation
![[staff] arpeggio mark](/img/45/0ee0089b947b467344b247839893d7.jpg)
[staff] arpeggio mark

Boost the rising point | yolov5 combined with alpha IOU

整型提升和大小端字节序

推荐10个好用到爆的Jupyter Notebook插件,让你效率飞起
随机推荐
C语言教程大全
@RequestParam
[C language] detailed explanation of C language to obtain array length
UPC -- expression evaluation
剑指offer II 091.粉刷房子
华为云计算之物理节点CNA安装教程
AttributeError: 'callable_iterator' object has no attribute 'next'
redis的入门学习到起飞,就这一篇搞定
Last 29 days
代码没写错,渲染页面不显示原因
4. use MySQL shell to install and deploy Mgr clusters | explain Mgr in simple terms
最后的二十九天
eyebeam高级设置
2 startup, interrupt and system call
How to open UMD, KMD log and dump diagrams in CAMX architecture
4~20mA输入/0~5V输出的I/V转换电路
[C#][转载]furion框架地址和教程地址
语音增强-频谱映射
Linux Mysql 实现root用户不用密码登录
The code is correct, and the rendering page does not display the reason