Java Xml 简明教程

Java JDOM Parser - Modify XML Document

Java JDOM 解析器是 Java 中的一个 API,它包含可修改 XML 文档的类和接口。此 API 会采用树结构的形式表示 XML 文档,并且可以轻松检索每个元素。因此,修改就会成为一项轻松的任务。我们可以使用 setText() 修改内容,并使用 addContent() 添加新元素。在本章中,我们将通过两个示例了解如何修改现有的 XML 文档。

Java JDOM parser is an API in java that has classes and interfaces to modify XML documents. This API represents the XML document in the form of a tree structure and each element can be retrieved easily. Hence, modification becomes an easy task. We can use setText() to modify content and addContent() to add new elements. In this chapter, we are going to see how to modify an existing XML document with two examples.

Modify XML using JDOM Parser

我们可以根据以下步骤通过 Java JDOM 解析器修改一个 XML 文档:

We can modify an XML document in java JDOM parser through following steps −

  1. *Step 1: *Creating a SAXBuilder Object

  2. *Step 2: *Reading the XML

  3. *Step 3: *Parsing the XML Document

  4. *Step 4: *Updating the content of XML document

  5. *Step 5: *Writing the content into XML file

  6. *Step 6: *Output to console for testing

如需了解前三个步骤,请参阅此部分的 second chapter

Refer second chapter of this section for first three steps.

Step 4: Updating the content of XML document

在完成前三个步骤后,我们已成功读取了需要更新的 XML 文档。现在,XML 文件采用 JDOM 文档的形式存在。要从该文档中获取任何信息,我们首先应始终获取根元素。在检索到根元素后,我们可以获取根内部所有元素的信息。

After following the first three steps, we have successfully read the XML document we need to update. Now, we have the XML file in the form of JDOM document. To get any information from the document, firstly, we should always get the root element. After retrieving the root element, we can get the information of all the elements inside the root.

如需了解步骤 5 和 6,请参阅此部分的 this chapter

Refer this chapter of this section for steps 5 and 6.

Updating Text Content

若要更新任何元素的文本内容,我们可以使用 Element 类的 setText() 方法。此方法将采用 String 形式的文本内容作为参数。如果文本内容已存在,则将旧文本内容更新为新文本内容。

To update text content of any element, we can use the setText() method of Element class. This method takes the text content as an argument in the form of a String. If text content already exists, it updates the old one with the new text content.

Example

在此,我们有 college.xml 文件,其中包含三个部门元素。我们将把 id 为 102 的部门的员工数量从 23 修改为 14。

Here, we have college.xml file that has three department elements. We are going to modify the staff count for department with id, 102 from 23 to 14.

<?xml version="1.0" encoding="UTF-8" standalone="no"?><college>
   <department id="101">
      <name>Computer Science</name>
      <staffCount>20</staffCount>
   </department>
   <department id="102">
      <name>Electrical and Electronics</name>
      <staffCount>23</staffCount>
   </department>
   <department id="103">
      <name>Mechanical</name>
      <staffCount>15</staffCount>
   </department>
</college>

以下 ModifyTextContent.java 程序使用 SAXBuilder 对象读取上述 college.xml 文件。在获取部门元素列表后,我们使用 getAttributeValue() 方法来查找 id 为 102 的部门。稍后,我们使用 setText() 方法更新文本内容。

The following ModifyTextContent.java program reads the above college.xml file using SAXBuilder object. After getting the list of department elements, we are using getAttributeValue() method to find the department with id, 102. Later, we are updating the text content using setText() method.

import java.io.File;
import java.util.List;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.input.SAXBuilder;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;
import org.jdom2.transform.JDOMSource;

public class ModifyTextContent {
   public static void main(String args[]) {
      try {

         //Creating a SAXBuilder Object
	     SAXBuilder saxBuilder = new SAXBuilder();

	     //Reading the XML
	     File inputFile = new File("college.xml");

	     //Parsing the XML Document
	     Document doc = saxBuilder.build(inputFile);

	     //Retrieving the Root Element
	     Element RootElement = doc.getRootElement();
	     List<Element> deptList = RootElement.getChildren("department");

	     //Finding "department" with id=102 in the list
	     for(int index=0; index<deptList.size();index++) {
	        Element department = deptList.get(index);
	        if(department.getAttributeValue("id").equals("102")) {
	           Element staffCount = department.getChild("staffCount");
	           //Updating the staff count
	           staffCount.setText("14");
	           break;
	        }
	     }
	     //writing the modified content into XML file
         TransformerFactory transformerFactory = TransformerFactory.newInstance();
         Transformer transformer = transformerFactory.newTransformer();
         JDOMSource source = new JDOMSource(doc);
         StreamResult result = new StreamResult(new File("college.xml"));
         transformer.transform(source, result);

         //Output to console for testing
         XMLOutputter xmlOutput = new XMLOutputter();
         xmlOutput.setFormat(Format.getPrettyFormat());
         xmlOutput.output(doc, System.out);
      } catch(Exception e) {
             e.printStackTrace();
	  }
   }
}

Output

以下是更新 staffCount 后的更新 XML 文档。

Following is the updated XML document after updating staffCount.

<?xml version="1.0" encoding="UTF-8" standalone="no"?><college>
   <department id="101">
      <name>Computer Science</name>
      <staffCount>20</staffCount>
   </department>
   <department id="102">
      <name>Electrical and Electronics</name>
      <staffCount>14</staffCount>
   </department>
   <department id="103">
      <name>Mechanical</name>
      <staffCount>15</staffCount>
   </department>
</college>

Adding New Elements

Element 类的 addContent() 方法获取子元素,并将其附加到当前元素的一个层次深度。它始终在末尾添加新元素。如果我们传递两个参数(索引和子元素),则子元素将插入指定的索引处。

The addContent() method of Element class takes child element and append it one level deep to the current element. It always adds the new Element at the end. If we pass two arguments, index and child element, then the child element gets inserted at the specified index.

Example

现在,我们将在以下 AddNewElements.java 程序中向我们的 college 元素中添加一个名为“Civil”的新部门。我们创建了部门的子元素,并将它们添加到部门元素。稍后我们将部门添加到根元素。

Now, we are going to add one more department named "Civil" to our college element in the following AddNewElements.java program. We have created the child elements of the department and added them to the department element. Later we added the department to the root element.

import java.io.File;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.input.SAXBuilder;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;
import org.jdom2.transform.JDOMSource;

public class AddNewElements {
   public static void main(String args[]) {
      try {

         //Creating a SAXBuilder Object
	     SAXBuilder saxBuilder = new SAXBuilder();

	     //Reading the XML
	     File inputFile = new File("college.xml");

	     //Parsing the XML Document
	     Document doc = saxBuilder.build(inputFile);

	     //Retrieving the Root Element
	     Element RootElement = doc.getRootElement();

	     //Creating new "department" Element
	     Element department=new Element("department");
	     department.setAttribute("id","104");

	     //Creating "name" Element for department
	     Element name=new Element("name");
	     name.setText("Civil");

	     //Creating "staffCount" Element for department
	     Element staffCount=new Element("staffCount");
	     staffCount.setText("18");

	     //Appending Elements
	     department.addContent(name);
	     department.addContent(staffCount);
	     RootElement.addContent(department);

	     //writing the modified content into XML file
         TransformerFactory transformerFactory = TransformerFactory.newInstance();
         Transformer transformer = transformerFactory.newTransformer();
         JDOMSource source = new JDOMSource(doc);
         StreamResult result = new StreamResult(new File("college.xml"));
         transformer.transform(source, result);

         //Output to console for testing
         XMLOutputter xmlOutput = new XMLOutputter();
         xmlOutput.setFormat(Format.getPrettyFormat());
         xmlOutput.output(doc, System.out);
      } catch(Exception e) {
             e.printStackTrace();
	  }
   }
}

Output

添加“Civil”部门后的更新文件如下:

The updated file after adding "Civil" department is as follows :

<?xml version="1.0" encoding="UTF-8"?>
<college>
  <department id="101">
    <name>Computer Science</name>
    <staffCount>20</staffCount>
  </department>
  <department id="102">
    <name>Electrical and Electronics</name>
    <staffCount>23</staffCount>
  </department>
  <department id="103">
    <name>Mechanical</name>
    <staffCount>15</staffCount>
  </department>
  <department id="104">
    <name>Civil</name>
    <staffCount>18</staffCount>
  </department>
</college>