如何使用Java StAX Iterator API用Java编写XML文件

时间:2020-02-23 14:36:16  来源:igfitidea点击:

Java 6中引入了用于XML的Java Streaming API或者Java StAX API,它被认为优于DOM和SAX解析器。
如先前有关Java StAX API的文章所述,它由基于游标的API和基于迭代器的API组成。

其中我们将看到如何使用基于StAX Iterator的API(XMLEventWriter)在Java中编写XML文件。

package com.theitroad.xml;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import javax.xml.stream.XMLEventFactory;
import javax.xml.stream.XMLEventWriter;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.events.Characters;
import javax.xml.stream.events.EndElement;
import javax.xml.stream.events.StartDocument;
import javax.xml.stream.events.StartElement;
import javax.xml.stream.events.XMLEvent;

public class StaxXMLWriter {

  public static void main(String[] args) {
      String fileName = "/Users/hyman/employee.xml";
      String rootElement = "Employee";
      StaxXMLWriter xmlWriter = new StaxXMLWriter();
      Map<String,String> elementsMap = new HashMap<String, String>();
      elementsMap.put("name", "hyman");
      elementsMap.put("age", "29");
      elementsMap.put("role", "Java Developer");
      elementsMap.put("gender", "Male");
      
      xmlWriter.writeXML(fileName, rootElement, elementsMap);
  }
  
  public void writeXML(String fileName, String rootElement, Map<String, String> elementsMap){
      XMLOutputFactory xmlOutputFactory = XMLOutputFactory.newInstance();
      try {
          XMLEventWriter xmlEventWriter = xmlOutputFactory
                  .createXMLEventWriter(new FileOutputStream(fileName), "UTF-8");
          //For Debugging - below code to print XML to Console
          //XMLEventWriter xmlEventWriter = xmlOutputFactory.createXMLEventWriter(System.out);
          XMLEventFactory eventFactory = XMLEventFactory.newInstance();
          XMLEvent end = eventFactory.createDTD("\n");
          StartDocument startDocument = eventFactory.createStartDocument();
          xmlEventWriter.add(startDocument);
          xmlEventWriter.add(end);
          StartElement configStartElement = eventFactory.createStartElement("",
              "", rootElement);
          xmlEventWriter.add(configStartElement);
          xmlEventWriter.add(end);
          //Write the element nodes
          Set<String> elementNodes = elementsMap.keySet();
          for(String key : elementNodes){
              createNode(xmlEventWriter, key, elementsMap.get(key));
          }
          
          xmlEventWriter.add(eventFactory.createEndElement("", "", rootElement));
          xmlEventWriter.add(end);
          xmlEventWriter.add(eventFactory.createEndDocument());
          xmlEventWriter.close();

      } catch (FileNotFoundException | XMLStreamException e) {
          e.printStackTrace();
      }
  }
  
  private static void createNode(XMLEventWriter eventWriter, String element,
          String value) throws XMLStreamException {
        XMLEventFactory xmlEventFactory = XMLEventFactory.newInstance();
        XMLEvent end = xmlEventFactory.createDTD("\n");
        XMLEvent tab = xmlEventFactory.createDTD("\t");
        //Create Start node
        StartElement sElement = xmlEventFactory.createStartElement("", "", element);
        eventWriter.add(tab);
        eventWriter.add(sElement);
        //Create Content
        Characters characters = xmlEventFactory.createCharacters(value);
        eventWriter.add(characters);
        //Create End node
        EndElement eElement = xmlEventFactory.createEndElement("", "", element);
        eventWriter.add(eElement);
        eventWriter.add(end);

      }

}

上面的程序创建下面的XML文件:

employee.xml

<?xml version="1.0" encoding="UTF-8"?>
<Employee>
	<age>29</age>
	<name>hyman</name>
	<gender>Male</gender>
	<role>Java Developer</role>
</Employee>

我已经使用\ n和\ t元素来创建格式化的XML,但是为了节省内存并减少处理时间,可以将其从实现中删除。

同样出于调试目的,您可以将输出流更改为System.out以将XML文件打印到控制台。