Java Xml 简明教程
Java JDOM Parser - Create XML Document
Java JDOM 解析器是 Java API,它具有用于从头开始创建 XML 文档的类和方法。我们可以创建一个新的 JDOM 文档对象,并使用文档和元素接口中提供的类添加元素和属性。在本教程中,我们将使用 setRootElement()、addContent()、setText() 和 setAttribute() 方法来详细创建 XML 文件。
Java JDOM Parser is a Java API that has classes and methods to create XML documents from scratch. We can create a new JDOM document object and add elements, attributes using the methods available in Document and Element interfaces. In this chapter, we are going to use setRootElement(), addContent(), setText() and setAttribute() methods to create XML files in detail.
Create XML using Java JDOM parser
我们可以在 Java 中使用 JDOM 解析器通过以下步骤来创建 XML 文档:
We can create an XML document in Java using JDOM parser through following steps −
-
*Step 1: *Creating JDOM Document object
-
*Step 2: *Creating and appending Root Element
-
*Step 3: *Creating elements and attributes
-
*Step 4: *Appending Elements to Root
-
*Step 5: *Writing the content into XML file
-
*Step 6: *Testing the output using console
Step 1: Creating JDOM Document object
org.jdom2 包中具有 Document 类。它表示 XML 文档。此类具有用于访问根元素以及文档级别信息的方法。我们如下创建一个新文档:
The org.jdom2 package has Document class. It represents the XML document. This class has methods to access the root element and also the document level information. We create a new document as follows −
Document doc = new Document();
Step 2: Creating and appending Root Element
一个 XML 文档必须包含一个根元素。我们使用 org.jdom2 包的 Element 类创建根元素。如果我们为构造器提供一个字符串,它会使用所提供的本地名称创建元素。
An XML document must contain a root element. We create root element using Element class of org.jdom2 package. If we provide a String to the constructor, it creates element with that supplied local name.
Document 类中的 setRootElement() 方法设置文档的根元素。此方法以 Element 作为参数,并将其设置为根元素。如果根元素已经存在,那么旧的根元素 Element 将被这个提供的 Element 替换。
The setRootElement() method in the Document class sets the root of the document. This method takes Element as an argument and sets it as the root. If the root element is already present, the old root Element gets replaced with this supplied Element.
Element RootElement = new Element("root");
doc.setRootElement(RootElement);
Step 3: Creating elements and attributes
我们可以像在上一步骤中创建根元素一样创建元素。若要设置 Element 的属性,我们使用 setAttribute() 方法,如下所示:
We can create Elements the same way we created root element in the previous step. To set an attribute to the Element, we use setAttribute() method as follows −
Element newElement = new Element("FirstElement");
newElement.setAttribute("attr_name","attr_value");
Step 4: Appending Elements to Root
在前一步创建的 Element 现在通过 addContent() 方法附加到根元素。此方法以内容列表的形式采用单个元素或元素集合,并将其添加到元素中。
The Elements created in the previous step are now attached to the root element using addContent() method. This method takes single element or collection of elements in the form of content list and adds them to the element accordingly.
RootElement.addContent(newElement);
Step 5: Writing the content into XML file
TransformerFactory 类用于创建 Transformer 对象的新实例。使用 Transformer 类中的 transform() 函数,源转换为目标结果。我们通过传递文档作为参数来创建 JDOMSource 对象。这个 JDOMSource 对象转换为 StreamResult,如下所示:
The TransformerFactory class is used to create a new instance of Transformer object. Using the transform() function in Transformer class, source is transformed to the destination result. We are creating JDOMSource object by passing document as a parameter. This JDOMSource object is transformed into StreamResult as follows −
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
JDOMSource source = new JDOMSource(doc);
StreamResult result = new StreamResult(new File("newFile.xml"));
transformer.transform(source, result);
Step 6: Testing the output using console
这是用于测试目的的可选步骤。为在控制台上打印输出,将创建 XMLOutputter 对象,并传递 Document 对象,如下所示:
This is an optional step used for testing purpose. To print the output on the console, an XMLOutputter object is created and the Document object is passed as follows −
XMLOutputter xmlOutput = new XMLOutputter();
xmlOutput.setFormat(Format.getPrettyFormat());
xmlOutput.output(doc, System.out);
Creating Simple XML File
使用以上步骤,让我们创建一个仅具有根元素的简单 XML 文件。将创建一个新的文档对象,并使用 {s0} 方法附加根元素。
Using, the above mentioned steps, let us create a simple XML file that has root element alone. A new document object is created and the Root element is attached using setRootElement() method.
Element 对象的 {s1} 方法以 String 的形式获取文本内容并将其附加到 Element。
The setText() method of Element object takes the text content in the form of a String and attaches it to the Element.
Example
以下是我们要创建的 XML 文件。它有一个名为“cars”的根元素和文本内容“Ferrari”。
Here is the XML file we need to create. It has a root element named "cars" and the text content, "Ferrari".
<cars>Ferrari</cars>
下面的 CreateXMLFile.java 创建 XML 文件,并以“cars.xml”为文件名存储在 D 驱动器中。
The following CreateXMLFile.java creates the XML file and stores it in D drive with the file name as "cars.xml".
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.output.Format;
import org.jdom2.output.XMLOutputter;
import org.jdom2.transform.JDOMSource;
public class CreateXMLFile {
public static void main(String[] args) {
try{
//Creating JDOM Document object
Document doc = new Document();
//Creating and appending Root Element
Element carsElement = new Element("cars");
carsElement.setText("Ferrari");
doc.setRootElement(carsElement);
//writing the content into XML file
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
JDOMSource source = new JDOMSource(doc);
StreamResult result = new StreamResult(new File("D:\\cars.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();
}
}
}
出于测试目的,我们在控制台上打印了 XML 文档的内容。
For testing purpose, we have printed the content of XML document on the console.
<?xml version="1.0" encoding="UTF-8"?>
<cars>Ferrari</cars>
Creating Attributes
现在让我们向根元素添加子元素。另外,让我们向元素添加属性。在此示例中,我们了解如何创建元素及其属性,以及如何将它们附加到根元素。每个元素上的 {s2} 方法设置属性,并使用 setText() 方法设置每个元素的文本内容。
Let us now add child elements to the root Element. Also, let us add attributes to our elements. In this example, we see how to create elements along with their attributes and attach them to the root. The setAttribute() method on each element sets the attribute and setText() method is used to set the text content of each element.
Example
以下是我们要创建的 cars.xml 文件:
Here is the cars.xml file that we need to create −
<cars>
<supercars company="Ferrari">
<carname type="formula one">Ferrari 101</carname>
<carname type="sports">Ferrari 202</carname>
</supercars>
</cars>
下面的 {s3} 程序在 D 驱动器中创建 cars.xml 文件。
The following CreateAttributes.java program creates the cars.xml file in D drive.
import java.io.File;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import org.jdom2.Attribute;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;
import org.jdom2.transform.JDOMSource;
public class CreateAttributes {
public static void main(String[] args) {
try{
//Creating JDOM Document object
Document doc = new Document();
//Creating and appending Root Element
Element carsElement = new Element("cars");
doc.setRootElement(carsElement);
//Creating elements and attributes
Element supercarElement = new Element("supercars");
supercarElement.setAttribute("company","Ferrari");
Element carElement1 = new Element("carname");
carElement1.setAttribute("type","formula one");
carElement1.setText("Ferrari 101");
Element carElement2 = new Element("carname");
carElement2.setAttribute("type","sports");
carElement2.setText("Ferrari 202");
supercarElement.addContent(carElement1);
supercarElement.addContent(carElement2);
//Appending Elements to Root
carsElement.addContent(supercarElement);
//writing the content into XML file
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
JDOMSource source = new JDOMSource(doc);
StreamResult result = new StreamResult(new File("D:\\Jdomcars.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();
}
}
}
输出窗口以如下内容显示文件内容:
The output window displays the file content as follows −
<?xml version="1.0" encoding="UTF-8"?>
<cars>
<supercars company="Ferrari">
<carname type="formula one">Ferrari 101</carname>
<carname type="sports">Ferrari 202</carname>
</supercars>
</cars>