Java Xml 简明教程

Java StAX Parser - Create XML Document

Java StAX 解析器是一个 Java API,提供创建 XML 文档的接口。包含光标 API(如 XMLStreamWriter)和迭代器 API(如 XMLEventWriter),用于创建 XML 文档。在本章中,我们将使用 XMLStreamWriter 来创建 XML 文档。该接口包括 writeStartDocument()、writeStartElement()、writeCharacters() 等方法,用于写入 XML 内容。

Java StAX parser is a Java API that provides interfaces to create XML documents. There are cursor APIs such as XMLStreamWriter and Iterator APIs such as XMLEventWriter to create XML documents. In this chapter, we are going to use XMLStreamWriter to create XML documents. This interface has methods such as writeStartDocument(), writeStartElement(), writeCharacters() etc., to write XML content.

Create XML using Java StAX parser

我们可以按照以下步骤,使用 StAX 解析器在 Java 中创建一个 XML 文档:

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

  1. *Step 1: *Creating XMLStreamWriter object

  2. *Step 2: *Writing the XML document

  3. *Step 3: *Creating XMLStreamReader object

  4. *Step 4: *Writing the content into file

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

Step 1: Creating XMLStreamWriter object

XMLOutputFactory 是一个用于创建 XMLEventWriters 和 XMLStreamWriters 的抽象类。我们可以使用 XMLEventWriter 或 XMLStreamWriter 对象来写入 XML 文档。

The XMLOutputFactory is an abstract class which is used to create XMLEventWriters and XMLStreamWriters. We can either use XMLEventWriter or XMLStreamWriter objects to write XML documents.

XMLOutputFactory 的 createXMLStreamWriter() 方法创建一个 XMLStreamWriter 对象,参数可以是 Writer、OutputStream 或任何 JAXP 结果。在此,我们创建了一个写入 Writer 流的 XMLStreamWriter。

The createXMLStreamWriter() method of XMLOutputFactory creates an XMLStreamWriter object and the argument can be a Writer, OutputStream or any JAXP result. Here, we have created an XMLStreamWriter that writes to a Writer stream.

XMLOutputFactory xMLOutputFactory = XMLOutputFactory.newInstance();
XMLStreamWriter xMLStreamWriter = xMLOutputFactory.createXMLStreamWriter(Writer stream);

Step 2: Writing the XML document

XMLStreamWriter 接口包含许多方法,用于指定如何编写 XML 文档。这些方法均有自解释性,不返回任何内容,而是将内容写入 Writer。以下列出了 XMLStreamWriter 接口中几种最常用的方法:

The XMLStreamWriter interface has many methods that specify how to write an XML document. They are self explanatory and does not return anything, but writes the content to the Writer. Following are the most commonly used methods of XMLStreamWriter interface −

xMLStreamWriter.writeStartDocument();
xMLStreamWriter.writeStartElement("cars");
xMLStreamWriter.writeCharacters("Ferrari");
xMLStreamWriter.writeEndElement();
xMLStreamWriter.writeEndDocument();

Step 3: Creating XMLStreamReader object

XMLInputFactory 是一个用于获取流的抽象类。使用 createXMLStreamReader() 方法,我们可以创建一个 XMLStreamReader 对象,能够读取指定的 InputStream。它提供向 XML 数据 InputStream 的前向、只读访问。

The XMLInputFactory is an abstract class for getting streams. Using createXMLStreamReader() method, we can create an XMLStreamReader object that allows us to read the InputStream specified. It gives forward, read-only access to the InputStream of XML data.

XMLInputFactory factory = XMLInputFactory.newInstance();
XMLStreamReader streamReader = factory.createXMLStreamReader(InputStream stream);

Step 4: Writing the content into file

Transformer 类中的 transform() 函数将 XML 源转换为结果。源的类型可以是 DOMSource、SAXSource、StAXSource 或 StreamSource,结果的类型可以是 DOMResult、SAXResult、StAXResult 或 StreamResult。

The transform() function of Transformer class tranforms the XML source to result. Source can be of type DOMSource, SAXSource, StAXSource or StreamSource and result can be of type DOMResult, SAXResult, StAXResult or StreamResult.

要创建 Transformer 对象,我们需要创建一个 TransformerFactory 实例。在此,源的类型是 StAXSource,结果的类型是 StreamResult。我们可以创建一个新的 File 对象,并将其作为参数传递给 StreamResult 对象。

To create Transformer object, we create an instance of TransformerFactory. Here, source is of type StAXSource and result is of type StreamResult. We can create a new File object and pass this as an argument to StreamResult object.

TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.transform(source, result);

Step 5: Testing the output using console

我们可以将“System.out”作为 StreamResult 的参数,在控制台上打印文件内容。Transformer 类的 transform() 方法将源转换为 StreamResult,并将其写入控制台。

We can print the file content on the console by passing 'System.out' as an argument for StreamResult. The transform() method of Transformer class converts the source into StreamResult and writes it on the console.

另一种打印结果的方法是,简单地将我们用于 XMLStreamWriter 的 Writer 对象转换为 String,然后再在控制台上打印该字符串。

Another way of printing the result is by simply converting the Writer object we have used for XMLStreamWriter into a String and printing that string on the console.

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

Creating Basic XML file

writeStartDocument() 方法将 XML 声明写入默认版本号为 1.0,编码为 utf-8。

The writeStartDocument() method writes the XML declaration with default version number as 1.0 and encoding as utf-8.

writeStartElement("element_name") 方法使用指定参数名作为元素名称打开新的起始标签。一旦我们指定相应的 EndElement,作用域将关闭。

The writeStartElement("element_name") method opens a new start tag with the specified argument name as the name of the element. The scope gets closed once we specify corresponding EndElement.

writeCharacters("text_content") 方法将指定的文本内容追加到元素。

The writeCharacters("text_content") method appends the specified text content to the Element.

Example

以下是我们想要创建的基本 XML 文件 -

Here is the basic XML file we want to create −

<?xml version="1.0" ?>
<cars>Ferrari</cars>

CreateBasicXML.java 程序使用 XMLStreamWriter 类创建 cars.xml 文件。我们使用 writeStartDocument() 方法写入 XML 声明,使用 writeStartElement("cars") 写入名为“cars”的新元素,以及使用 writeCharactrs("Ferrari") 写入文本内容。我们使用 writeEndElement() 和 writeEndDocument() 方法正确关闭作用域。

The CreateBasicXML.java program creates cars.xml file using XMLStreamWriter class. We have used the methods writeStartDocument() to write the XML declaraction, writeStartElement("cars") to write the new Element named, "cars" and writeCharactrs("Ferrari") to write the text content. We have used writeEndElement() and writeEndDocument() methods to close the scopes correctly.

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.StringWriter;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamReader;
import javax.xml.stream.XMLStreamWriter;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stax.StAXSource;
import javax.xml.transform.stream.StreamResult;

public class CreateBasicXML {
   public static void main(String[] args) throws TransformerException {
      try {

         //creating XMLStreamWriter
         XMLOutputFactory xMLOutputFactory = XMLOutputFactory.newInstance();
         StringWriter stringWriter = new StringWriter();
         XMLStreamWriter xMLStreamWriter =
            xMLOutputFactory.createXMLStreamWriter(stringWriter);

         //Writing the XML document
         xMLStreamWriter.writeStartDocument();
         xMLStreamWriter.writeStartElement("cars");
         xMLStreamWriter.writeCharacters("Ferrari");
         xMLStreamWriter.writeEndElement();
         xMLStreamWriter.writeEndDocument();
         xMLStreamWriter.flush();
         xMLStreamWriter.close();

         //Creating XMLStreamReader object
         String xmlString = stringWriter.getBuffer().toString();
         ByteArrayInputStream input = new ByteArrayInputStream(xmlString.getBytes("UTF-8"));
         stringWriter.close();
         XMLInputFactory factory = XMLInputFactory.newInstance();
         XMLStreamReader streamReader =
                 factory.createXMLStreamReader(input);

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

         //Testing the output using console
         System.out.println(xmlString);

      } catch (Exception e) {
         e.printStackTrace();
      }
   }
}

Output

我们使用 XMLStreamWriter 写入的 XML 文档显示如下 -

The XML document we have written using XMLStreamWriter is displayed as follows −

<?xml version="1.0" ?><cars>Ferrari</cars>

Creating XML file with Attributes

writeAttribute("attr_name","attr_value") 方法将属性追加到当前元素。它应写入在 writeStartElement() 和 witeEndElement() 方法之间。如果将此方法不正确地置于元素范围之外,它会导致 IllegalStateException 错误。

The writeAttribute("attr_name","attr_value") method appends the attribute to the current element. It should be written between writeStartElement() and witeEndElement() methods. If this method is placed incorrectly out of scope of an element, it throws IllegalStateException error.

Example

我们必须创建以下 cars.xml 文件 -

We have to create the following cars.xml file −

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

在以下 CreateAttributes.java 程序中,我们在 supercar 元素下创建了两个 carname 元素以及属性。

In the following CreateAttributes.java program, we have created two carname elements under supercar element along with attributes.

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.StringWriter;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamReader;
import javax.xml.stream.XMLStreamWriter;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stax.StAXSource;

public class CreateAttributes {
   public static void main(String[] args) throws TransformerException {
      try {

    	 //creating XMLStreamWriter
         XMLOutputFactory xMLOutputFactory = XMLOutputFactory.newInstance();
         StringWriter stringWriter = new StringWriter();
         XMLStreamWriter xMLStreamWriter =
            xMLOutputFactory.createXMLStreamWriter(stringWriter);

         //Writing the XML document
         xMLStreamWriter.writeStartDocument();
         xMLStreamWriter.writeStartElement("cars");

         xMLStreamWriter.writeStartElement("supercars");
         xMLStreamWriter.writeAttribute("company", "Ferrari");

         xMLStreamWriter.writeStartElement("carname");
         xMLStreamWriter.writeAttribute("type", "formula one");
         xMLStreamWriter.writeCharacters("Ferrari 101");
         xMLStreamWriter.writeEndElement();

         xMLStreamWriter.writeStartElement("carname");
         xMLStreamWriter.writeAttribute("type", "sports");
         xMLStreamWriter.writeCharacters("Ferrari 202");
         xMLStreamWriter.writeEndElement();

         xMLStreamWriter.writeEndElement();
         xMLStreamWriter.writeEndDocument();

         xMLStreamWriter.flush();
         xMLStreamWriter.close();

         //Creating XMLStreamReader object
         String xmlString = stringWriter.getBuffer().toString();
         ByteArrayInputStream input = new ByteArrayInputStream(xmlString.getBytes("UTF-8"));
         stringWriter.close();
         XMLInputFactory factory = XMLInputFactory.newInstance();
         XMLStreamReader streamReader =
                 factory.createXMLStreamReader(input);

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

         //Testing the output using console
         System.out.println(xmlString);

      } catch (Exception e) {
         e.printStackTrace();
      }
   }
}

Output

输出窗口显示使用 XMLStreamWriter 生成的 XML 内容。

The output window displays the XML content generated using XMLStreamWriter.

<?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>