Java Xml 简明教程

Java DOM Parser - Create XML Document

Java DOM 解析器 API 有方法、接口和类来创建 XML 文档。使用此 API,我们可以通过 Java 应用程序从头创建 XML 文档。createElement() 方法创建新元素,而 appendChild() 方法将创建的元素追加到已存在的元素。

Java DOM parser API has methods, interfaces and classes to create XML documents. Using this API, we can create XML documents from the scratch through our Java applications. The createElement() method creates new elements and the appendChild() method appends the created elements to already existing elements.

Create XML Using Java DOM Parser

我们可以通过以下步骤使用 DOM 解析器在 Java 中创建一个 XML 文档 -

We can create an XML document in Java using DOM parser through following steps −

  1. *Step 1: *Creating a DocumentBuilder Object

  2. *Step 2: *Create a new Document

  3. *Step 3: *Creating the root element

  4. *Step 4: *Appending elements to the root element

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

  6. *Step 6: *Testing the output using console

步骤 1,请参阅 this page

Refer this page for step 1.

Step2: Create a new Document

使用在上一步中创建的 DocumentBuilder 对象,使用 newDocument() 函数创建一个新文档。

Using DocumentBuilder object created in the above step, create a new document with newDocument() function.

Document doc = dBuilder.newDocument();

Step3: Creating the root element

每个 XML 文档都应包含一个单一的根元素,也称为父元素。我们可以使用 createElement() 方法创建根元素并将其附加到上一步中创建的文档中。

Every XML document should possess a single root element , which is also called a parent element. We can create the root element using createElement() method and append it to the document created in the previous step.

Element rootElement = doc.createElement("root");
doc.appendChild(rootElement);

Step 4: Appending elements to the root element

在根元素内部,我们可以创建任意数量的子元素,并以与将根元素附加到文档相同的方式将其附加。要写入元素内的文本内容,我们可以使用 createTextNode() 方法。我们还可以使用 createAttribute() 方法为元素创建属性。

Inside the root element, we can create any number of child elements and append them the same way we appended root element to the document. To write text content inside an element, we can use createTextNode() method. We can also create attributes for elements using createAttribute() method.

Element child = doc.createElement("child");
rootElement.appendChild(child);
child.appendChild(doc.createTextNode("text_content_here"));
Attr attr = doc.createAttribute("child");

Step 5: Writing the content into XML file

在使用相应的属性构建文档内的元素后,我们需要将此内容写入 XML 文件,方法是创建 Tranformer 对象,它反过来将我们的源文档转换为 StreamResult,并将其存储在给定名称的指定文件路径中。

After building the elements inside the document with their corresponding attributes, we need to write this content into an XML file by creating Tranformer object, which in-turn transforms our source document into StreamResult and stores it in the specified file path with the given name.

TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File("filepath:\\new.xml"));
transformer.transform(source, result);

Step 6: Testing the output using console

我们可以通过在控制台上打印 XML 文件来测试它。这是一个可选步骤。

We can test our XML file by printing it on the console. This is an optional step.

StreamResult consoleResult = new StreamResult(System.out);
transformer.transform(source, consoleResult);

Creating Basic XML File

为了创建一个文档元素,我们使用 createElement("element_name") 方法。此方法将元素名称作为参数,并返回一个新的 Element 对象。

To create a document element, we use the method createElement("element_name"). This method takes element name as an argument and returns a new Element object.

在获得新的 Element 对象后,我们可以使用 appendChild(Element) 方法将此 Element 对象附加到文档。此方法还用于将一个元素附加到另一个元素(创建子元素)。

After getting the new Element object, we can use appendChild(Element) method to append this Element object to the document. This method is also used to append an element to another element (creating child elements).

cars.xml

我们希望在 D 驱动器中创建名为“cars.xml”的以下 xml 文件。

We want to create the following xml file with the name "cars.xml" in D drive.

<cars>
<supercars>Ferrari</supercars>
</cars>

CreateXMLDemo.java

在以下代码中,我们创建了一个名为“cars”的根元素,并附加了一个名为“supercars”的子元素。我们还向 supercars 元素添加了文本内容。

In the following code, we have created one root element with name "cars" and appended one child element with name "supercars". We have also added text content to supercars element.

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import java.io.File;

public class CreateXMLDemo {

   public static void main(String argv[]) {

      try {

    	 //Creating a DocumentBuilder Object
         DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
         DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();

         //Create a new Document
         Document doc = dBuilder.newDocument();

         //Creating the root element
         Element rootElement = doc.createElement("cars");
         doc.appendChild(rootElement);

         //Appending elements to the root element
         Element supercar = doc.createElement("supercars");
         rootElement.appendChild(supercar);
         supercar.appendChild(doc.createTextNode("Ferrari"));

         //writing the content into XML file
         TransformerFactory transformerFactory = TransformerFactory.newInstance();
         Transformer transformer = transformerFactory.newTransformer();
         DOMSource source = new DOMSource(doc);
         StreamResult result = new StreamResult(new File("D:\\cars.xml"));
         transformer.transform(source, result);

         //Output to console for testing
         StreamResult consoleResult = new StreamResult(System.out);
         transformer.transform(source, consoleResult);
      } catch (Exception e) {e.printStackTrace();}
   }
}

Output

为了测试,我们在控制台上打印了文档输出。

For testing, we have printed the document output on the console.

<?xml version="1.0" encoding="UTF-8" standalone="no"?><cars><supercars>Ferrari</supercars></cars>

Creating XML File with Attributes

可以使用 createAttribute("Attribute_name") 方法为元素创建属性。Document 接口的此方法将属性的名称作为参数,并返回 Attr 对象。 setValue("value") 方法用于设置属性的值。

Attributes can be created to an Element using the method, createAttribute("Attribute_name"). This method of Document interface takes name of the attribute as an argument and returns the Attr object. The setValue("value") method is used to set the value of the attribute.

现在,要将此属性节点设置到 Element,我们使用 setAttributeNode(Attr) 方法和需要设置此属性的 Element 对象。

Now, to set this attribute node to the Element, we use setAttributeNode(Attr) method with the Element object to which we need to set this attribute.

newcars.xml

我们需要在 D 驱动器中创建以下“newcars.xml”。

We need to create the following "newcars.xml" in D drive.

<cars>
<supercars company="Ferrari">
<carname type="formula one">Ferrari 101</carname>
<carname type="sports">Ferrari 202</carname>
</supercars>
</cars>

CreateXMLAttributeDemo.java

我们为 supercars 元素创建了两个 carname 元素。此外,通过使用 setAttributeNode() 方法,我们为每个 carname 元素添加了两个属性。

We have created two carname elements for supercars element. Also, using setAttributeNode() method, we have added two attributes for each of the carname elements.

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import java.io.File;

public class CreateXMLAttributeDemo {

   public static void main(String argv[]) {

      try {

    	 //Creating a DocumentBuilder Object
         DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
         DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();

         //Creating a new Document
         Document doc = dBuilder.newDocument();

         //Creating the root element
         Element rootElement = doc.createElement("cars");
         doc.appendChild(rootElement);

         //Appending sub element to the root element
         Element supercar = doc.createElement("supercars");
         rootElement.appendChild(supercar);

         //Setting attribute to the sub element
         Attr attr = doc.createAttribute("company");
         attr.setValue("Ferrari");
         supercar.setAttributeNode(attr);

         //Adding First child element to sub element
         Element carname = doc.createElement("carname");
         Attr attrType = doc.createAttribute("type");
         attrType.setValue("formula one");
         carname.setAttributeNode(attrType);
         carname.appendChild(doc.createTextNode("Ferrari 101"));
         supercar.appendChild(carname);

         //Adding second child element to sub element
         Element carname1 = doc.createElement("carname");
         Attr attrType1 = doc.createAttribute("type");
         attrType1.setValue("sports");
         carname1.setAttributeNode(attrType1);
         carname1.appendChild(doc.createTextNode("Ferrari 202"));
         supercar.appendChild(carname1);

         //writing the content into XML file
         TransformerFactory transformerFactory = TransformerFactory.newInstance();
         Transformer transformer = transformerFactory.newTransformer();
         DOMSource source = new DOMSource(doc);
         StreamResult result = new StreamResult(new File("D:\\newcars.xml"));
         transformer.transform(source, result);

         //Output to console for testing
         StreamResult consoleResult = new StreamResult(System.out);
         transformer.transform(source, consoleResult);
      } catch (Exception e) { e.printStackTrace(); }
   }
}

Output

为了测试,我们在控制台上打印了文档输出。

For testing, we have printed the document output on the console.

<?xml version="1.0" encoding="UTF-8" standalone="no"?><cars><supercars company="Ferrari"><carname type="formula one">Ferrari 101</carname><carname type="sports">Ferrari 202</carname></supercars></cars>