Java Xml 简明教程
Java DOM4J Parser - Modify XML Document
Java DOM4J API 提供了修改 XML 文档的方法。我们可能会遇到需要在一个较大的 XML 文档中更新几个详细信息的情况。例如,电子商务网站有很多产品,其价格可能每天或每月都会变化。在这种情况下,修改现有文件比重新创建 XML 文档更简单。在本章中,我们将通过一些示例学习如何使用 DOM4J API 修改现有的 XML 文档。
Java DOM4J API provides methods to modify XML documents. We might come across situations where we need to update few details in a large XML document. For example, an e-commerce website has many products whose price may vary on a daily or monthly basis. In such cases, modifying the already existing file makes the job simpler than to create the XML documents again. In this chapter, we are going to look at some examples to learn how to modify existing XML documents using DOM4J API.
Modify XML Using Java DOM4J Parser
以下是使用 Java DOM4J 解析器修改 XML 文档的步骤:
Following are the steps to modify XML documents using Java DOM4J Parser −
-
*Step 1: *Creating SAXReader object
-
*Step 2: *Reading the XML file
-
*Step 3: *Parsing the XML
-
*Step 4: *Extracting the root
-
*Step 5: *Modifying the elements
-
*Step 6: *Creating a FileOutputStream
-
*Step 7: *Writing the updated XML document into file
-
*Step 8: *Printing the XML document
请参阅本节的 Parse XML Document 章节以了解前四个步骤。
Refer Parse XML Document chapter of this section for the first four steps.
Step 5: Modifying the elements
在步骤 4 中提取根元素后,我们可以使用 elements() 方法获取其任何子元素。我们可以通过编辑文本内容、更改属性值、添加新属性等方式来修改已存在的元素。
After extracting the root element in step 4, we can get any of its child elements by using the elements() method. We can modify already existing elements by editing their text content, changing attribute values, adding new attributes etc.
请参阅本节的 Create XML Document 章节以了解后三个步骤。
Refer Create XML Document chapter of this section for the last three steps.
Modify Text Content
若要修改元素的文本内容,我们可以使用 setText() 方法来设置文本内容。它采用字符串作为参数,并将旧文本内容更新为新文本内容。此方法可在 Node 和 Element 接口中获得。
To modify text content of an element, we can use the method setText() to set the text content. It takes a string as an argument and updates the old text content with the new text content. This method is available in both Node and Element interfaces.
Example
在以下 studentData.xml 文件中,我们需要为学号为 493 的学生将分数从 80 更新为 64。
In the following studentData.xml file, We need to update marks from 80 to 64 for the student with roll number 493.
<?xml version="1.0" encoding="UTF-8"?>
<class>
<student rollno="393">
<firstname>dinkar</firstname>
<lastname>kad</lastname>
<nickname>dinkar</nickname>
<marks>85</marks>
</student>
<student rollno="493">
<firstname>Vaneet</firstname>
<lastname>Gupta</lastname>
<nickname>vinni</nickname>
<marks>80</marks>
</student>
<student rollno="593">
<firstname>jasvir</firstname>
<lastname>singn</lastname>
<nickname>jazz</nickname>
<marks>90</marks>
</student>
</class>
以下 ModifyTextContent.java 程序使用 SAXReader 读取上述 studentData.xml 文件。使用 elementIterator("student") 方法,我们在 Iterator 中获取所有学生元素。我们迭代所有元素以使用 attributeValue() 方法查找学号为 493 的学生,然后更新 marks 元素的文本内容。
The following ModifyTextContent.java program reads the above studentData.xml file using SAXReader. Using elementIterator("student") method, we got all the student elements in an Iterator. We iterate all the elements to find the student with roll number 493 using attributeValue() method and updates the text content of marks element.
import java.io.File;
import java.io.FileOutputStream;
import java.util.Iterator;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
public class ModifyTextContent {
public static void main(String[] args) {
try {
//Creating SAXReader
SAXReader reader = new SAXReader();
//Reading the XML file
File inputFile = new File("studentData.xml");
//Parsing the XML
Document document = reader.read(inputFile);
//Extracting the root
Element RootElement = document.getRootElement();
//Modifying the elements
Iterator<Element> students = RootElement.elementIterator("student");
while(students.hasNext()) {
Element student = students.next();
if(student.attributeValue("rollno").equals("493")) {
Element marks = student.element("marks");
marks.setText("64");
}
}
//Creating a FileOutputStream
FileOutputStream newFile = new FileOutputStream("studentData.xml");
//Writing the updated XML document into file
XMLWriter writer = new XMLWriter(newFile);
writer.write( document );
//Printing the XML document
OutputFormat format = OutputFormat.createPrettyPrint();
XMLWriter consoleWriter = new XMLWriter( System.out, format );
consoleWriter.write( document );
} catch(Exception e) {
e.printStackTrace();
}
}
}
Output
学号为 493 的学生的成绩已从 80 更新为 64。
Marks for the student with roll number 493 is updated from 80 to 64.
<?xml version="1.0" encoding="UTF-8"?>
<class>
<student rollno="393">
<firstname>dinkar</firstname>
<lastname>kad</lastname>
<nickname>dinkar</nickname>
<marks>85</marks>
</student>
<student rollno="493">
<firstname>Vaneet</firstname>
<lastname>Gupta</lastname>
<nickname>vinni</nickname>
<marks>64</marks>
</student>
<student rollno="593">
<firstname>jasvir</firstname>
<lastname>singn</lastname>
<nickname>jazz</nickname>
<marks>90</marks>
</student>
</class>
Add New Elements
addElement() 方法向现有 XML 文稿添加新元素,将其置于该当前元素所有已存在的子元素末尾。我们需要将该元素的标签名称传递为参数。类似地,addText() 方法向该元素添加文本内容。 addAttribute() 将新属性添加到当前元素。我们需要将属性名称和属性值传递为参数。
The addElement() method adds new elements to an existing XML document at the end of all the already existing child elements of that current element. We need to pass the tag name of the element as an argument. Similarly, the addText() method adds text content to the element. The addAttribute() adds new attribute to the current element. We need to pass attribute name and attribute value as arguments.
以下 AddNewElements.java 程序读取我们在前一个示例中使用的 studentData.xml 文件,并使用上述方法添加新学生的详细信息。
The following AddNewElements.java program reads the studentData.xml file we have used in the previous example and uses the above methods to add information of a new student.
import java.io.File;
import java.io.FileOutputStream;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
public class AddNewElements {
public static void main(String[] args) {
try {
//Creating SAXReader
SAXReader reader = new SAXReader();
//Reading the XML file
File inputFile = new File("studentData.xml");
//Parsing the XML
Document document = reader.read(inputFile);
//Extracting the root
Element RootElement = document.getRootElement();
//Modifying the elements
Element student = RootElement.addElement("student").addAttribute("rollno", "693");
student.addElement("firstname").addText("John");
student.addElement("lastname").addText("Daniel");
student.addElement("nickname").addText("Johny");
student.addElement("marks").addText("78");
//Creating a FileOutputStream
FileOutputStream newFile = new FileOutputStream("studentData.xml");
//Writing the updated XML document into file
XMLWriter writer = new XMLWriter(newFile);
writer.write( document );
//Printing the XML document
OutputFormat format = OutputFormat.createPrettyPrint();
XMLWriter consoleWriter = new XMLWriter( System.out, format );
consoleWriter.write( document );
} catch(Exception e) {
e.printStackTrace();
}
}
}
Output
添加新学生信息后的文件内容如下:
The file content after adding new student information is as follows −
<?xml version="1.0" encoding="UTF-8"?>
<class>
<student rollno="393">
<firstname>dinkar</firstname>
<lastname>kad</lastname>
<nickname>dinkar</nickname>
<marks>85</marks>
</student>
<student rollno="493">
<firstname>Vaneet</firstname>
<lastname>Gupta</lastname>
<nickname>vinni</nickname>
<marks>64</marks>
</student>
<student rollno="593">
<firstname>jasvir</firstname>
<lastname>singn</lastname>
<nickname>jazz</nickname>
<marks>90</marks>
</student>
<student rollno="693">
<firstname>John</firstname>
<lastname>Daniel</lastname>
<nickname>Johny</nickname>
<marks>78</marks>
</student>
</class>