One 、 establish XML

// establish XML
public static void gernatorXML() {
// establish Document object
Document doc = DocumentHelper.createDocument();
// Create a root node students
Element studentsElement = doc.addElement("students");
// Create child nodes student
Element studentElement1 = studentsElement.addElement("student");
// add to ID attribute
studentElement1.addAttribute("id", "1001");
// Add child nodes
studentElement1.addElement("name").setText(" Zhang San ");
studentElement1.addElement("age").setText("18");
studentElement1.addElement("sex").setText(" male ");
studentElement1.addElement("phone").setText("13800138000");
studentElement1.addElement("address").setText(" Shenzhen Bao'an "); // Create the same 2 individual student node
Element studentElement2 = studentsElement.addElement("student");
// add to ID attribute
studentElement2.addAttribute("id", "10012");
// Add child nodes
studentElement2.addElement("name").setText(" Li Si ");
studentElement2.addElement("age").setText("19");
studentElement2.addElement("sex").setText(" Woman ");
studentElement2.addElement("phone").setText("13412369854");
studentElement2.addElement("address").setText(" Shanghai ");
// Create the same 2 individual student node
Element studentElement3 = studentsElement.addElement("student");
// add to ID attribute
studentElement3.addAttribute("id", "10013");
// Add child nodes
studentElement3.addElement("name").setText(" Wang Wu ");
studentElement3.addElement("age").setText("25");
studentElement3.addElement("sex").setText(" Woman ");
studentElement3.addElement("phone").setText("13410110104");
studentElement3.addElement("address").setText(" guangdong "); try {
// establish XML take Document write in XML
// Format
OutputFormat format = OutputFormat.createPrettyPrint();
// Setting character encoding can also be set to gb2312 perhaps gbk
format.setEncoding("utf-8");
// Input
XMLWriter writer = new XMLWriter(
new FileWriter("xml/students.xml"), format); // Written document
writer.write(doc);
// Closed flow
writer.close();
// Output hint
System.out.println("====== Write successfully =======");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

Two 、 analysis XML

 // Read XML
public static void getXML() { try {
// Read XML
SAXReader reader = new SAXReader();
Document doc = reader.read("xml/students.xml");
// Get root node
Element root = doc.getRootElement();
// Get the collection of child nodes
List<Element> stulList = root.elements();
// Traverse
for (Element ele : stulList) {
// get attribute
String id = ele.attributeValue("id");
System.out.println(" Student ID: " + id);
// Get the text content of the child node name
String name = ele.elementText("name");
// age Age
String age = ele.elementText("age");
// sex
String sex = ele.elementTextTrim("sex");
// phone
String phone = ele.elementTextTrim("phone");
// address
String address = ele.elementTextTrim("address");
System.out.println(" full name :" + name + "\t Age : " + age + "\t Gender : "
+ sex + "\t\t Telephone :" + phone + "\t\t Address : " + address);
} } catch (DocumentException e) {
e.printStackTrace();
} }

3、 ... and 、 Add node

// Add new nodes 
public static void addXML(){ try {
// Read XML Create a parser
SAXReader reader=new SAXReader();
// establish Document object
Document doc=reader.read("xml/students.xml");
// Get root node
Element root=doc.getRootElement();
// Create a new node
Element student=root.addElement("student");
// Add attribute
student.addAttribute("id", "10020");
// Create child nodes
student.addElement("name").setText(" Zhang Sanfeng ");
student.addElement("age").setText("108");
student.addElement("sex").setText(" male ");
student.addElement("phone").setText("13800138001");
student.addElement("address").setText(" Wudang Mountain ");
// write in XML
// Set character encoding and formatting
OutputFormat format=new OutputFormat();
format.setEncoding("utf-8");
// Create output stream
XMLWriter writer=new XMLWriter(new FileWriter("xml/students.xml"), format);
// write in Document
writer.write(doc);
// Closed flow
writer.close();
// Give hints
System.out.println("====== Increase success ======="); } catch (DocumentException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} }

Four 、 Modify node

// Modify the content of the node according to id10013 Will Wang Wu's name = Wang Xiaowu , Age 30, Gender : male , Telephone :138000138000, Address : Beijing 
public static void modify(){ try {
// establish SAXReader Parser
SAXReader reader=new SAXReader();
// establish Document
Document doc=reader.read("xml/students.xml");
// Find the root node
Element root=doc.getRootElement();
// Set of child nodes
List<Element> studentList=root.elements();
// Traversal search
for (Element ele : studentList) { if(ele.attributeValue("id").equals("10013")){
ele.element("name").setText(" Wang Xiaowu ");
ele.element("age").setText("30");
ele.element("sex").setText(" male ");
ele.element("phone").setText("138000138000");
ele.element("address").setText(" Beijing "); }
}
// write in XML
// Format and encode characters
OutputFormat format=new OutputFormat();
format.setEncoding("utf-8");
XMLWriter writer=new XMLWriter(new FileWriter("xml/students.xml"), format);
// take Document write in
writer.write(doc);
// Closed flow
writer.close();
// Give hints
System.out.println("==== Modification successful ===="); } catch (DocumentException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

5、 ... and 、 Delete node XML

/ Delete node Delete Wang Xiaowu's node 
public static void delete(){ try {
// establish SAXReader Parser
SAXReader reader=new SAXReader();
// establish Document object
Document doc=reader.read("xml/students.xml");
// Get root node
Element root=doc.getRootElement();
// aggregate
List<Element> stuList=root.elements();
// Traverse
for (Element ele : stuList) {
if(ele.attributeValue("id").equals("10013")){
// Get parent node , And delete this node
ele.getParent().remove(ele);
}
}
// write in XML
// Set character encoding format
OutputFormat format =new OutputFormat();
format.setEncoding("utf-8");
// Output stream
XMLWriter writer=new XMLWriter(new FileWriter("xml/students.xml"), format);
writer.write(doc);
writer.close();
System.out.println("=== Delete successful ==="); } catch (DocumentException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

Java Learn from scratch (DOM4j analysis XML) More articles about

  1. Java Advanced ( twenty-seven ) Use Dom4j analysis XML file

    Use Dom4j analysis XML file Let me write it out front Due to the experimental requirements of the paper , You need to implement the operation XML file , So I thought of dom4j This tool , After using it, I deeply benefit . Let's share with you , To encourage . notes : Reprinted from http://blog. ...

  2. stay java How to use Dom4j analysis XML File access data

    In the past study .net We often encounter using configuration file to solve some data that need to be changed frequently in the project . For example, the connection string of the database . This time when reading the configuration file . We usually use a ray configuration, Through this class to enter ...

  3. Java Learn from scratch (DOM analysis XML)

    One .DOM analysis XML xml file favorite.xml <?xml version="1.0" encoding="UTF-8" standalone ...

  4. Java Learn from scratch (Socket Programming based )

    One . There are two main problems in network programming One is how to accurately locate one or more hosts on the network , The other is how to transfer data reliably and efficiently after finding the host . stay TCP/IP Agreement IP Layer is mainly responsible for the location of network hosts , Routing of data transmission , from IP The address can be ...

  5. Java Learn from scratch (JAVA IO- File class )

    One . sketch Throughout io In bag , The only class that says something about the file itself is File class . Use File Class can create or delete files and other common operations . Want to use File class , First of all, we should observe File Construction method of class , The common construction methods of this class are as follows : ...

  6. Java Learn from scratch ( Note brief )

    One .Java Notes in Annotation What is annotation : Data used to describe data ( Metadata ). Java Special tags in code . It adds... To the code Java Additional information that a program cannot express provides a formal way , We can use it sometime in the future ...

  7. Java Learn from scratch ( Multithreading )

    One . Processes and threads 1.1. process A process is an instance of an application . A process is a dynamic execution of a program , It went through loading from code . A complete process from execution to the end of execution , This process is also the process itself . The process of development to its final demise features : dynamic ...

  8. Java Learn from scratch ( Reflection 2 )

    One . Instantiation Class Class object Instantiation Class There are three methods for class objects : The first one is : adopt forName() Method The second kind : class .class The third kind of : object .getClass() Two .Class Common methods of class No. Fang ...

  9. Java Learn forty from scratch ( A reflection is a reflection )

    One .JAVA Is it dynamic language ? generally speaking , When it comes to dynamic speech , It means that the program structure or variable type can be changed when the program is running , From this point of view ,JAVA and C++ equally , It's not a dynamic language . but JAVA It has a very prominent dynamic correlation mechanism : back ...

Random recommendation

  1. 【UEditor】 UEditor Integrate project upload resources to Alibaba cloud server

    Catalog About this article Download the source code JSP Code Java Code Alibaba cloud jar Package import configuration It's a success ! Back to the top About this article Project to achieve the editor to generate a formatted html file , Save the template , The last generation html Of URL, So I chose UE ...

  2. About Domain Driven Design (DDD) Thinking about warehousing

    Why storage ? Domain object ( It's usually aggregate roots ) You need to deal with the database from creation to persistence , In this way, we need something similar to database access layer to manage domain objects . Is it possible for us to design a similar one DAL The east of the floor ...

  3. virtualbox Install on virtual machine centOS Network configuration ( install centos Select the bridge network when you want to )

    Recent contact hadoop, Need to be in Linux The above development , So I installed a virtualbox virtual machine , A centOS System .linux The system is installed , But network configuration is a headache . I mainly want the host to ...

  4. Image Generator (Image Builder)

    If you want to download a pre compiled image file , Or you want to try the whole compilation process , An alternative is to use a mirror generator (Image Generator)( It used to be called Image Builder). This is a pre compiled OpenWrt ...

  5. ASP Two ways to page long articles , function

    ' Manual pagination by logo function manualPage(str) pages=request.QueryString("page") contentstr=split(str,& ...

  6. NetworkX Learning notes -5-NetworkX How to assign attributes to multiple networks in , And sort by attributes

    This is a practical problem I encountered in the process of data analysis , Take a brief note of . Here we use DiGraph For example , Other types of networks ( chart ) It's the same way . Follow here :http://networkx.github.io/documenta ...

  7. DataTable Filter the maximum value of a column

    dt.Compute("max( Name )",""); Compute There are only two arguments to the function :Expression, and Filter. Expresstion It's a computational expression , ...

  8. Chapter one 、vlc-android It's the beginning of

    Reprint please indicate the source :http://blog.csdn.net/cuiran/article/details/30054835 I've been studying android The live video part of , Play local video files directly from the beginning , To make ...

  9. oracle 11g Empty table leads to no problem

    Query empty table ' Generate execution statements that allocate space or num_rows is null Copy it and execute it .

  10. WCF Use net.tcp Binding configuration instance

    <system.serviceModel> <bindings> <basicHttpBinding> <!-- Default http Configuration of bindings , This improves the maximum transmission information ...