如何从XML文件的解析数据输出创建单个XML文件?

时间:2015-02-26 15:30:04

标签: java android xml parsing dom

我编写了一个解析XMl文件数据的程序(DOM Parser)。我想为从xml文档解析的每组数据创建一个具有相应名称的单个文件。如果解析的输出是Single,Double,Triple,我想创建一个具有相应名称的单个xml文件(Single.xml,Double.xml,Triple.xml)。如何创建xml文件并为每个文件指定解析数据输出的名称?在此先感谢您的帮助。

import java.io.IOException;


import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class MyDomParser {

  public static void main(String[] args) {
  DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
  try {
  DocumentBuilder builder = factory.newDocumentBuilder();
  Document doc = builder.parse("ENtemplate.xml");
  doc.normalize();

  NodeList rootNodes = doc.getElementsByTagName("templates");
  Node rootNode = rootNodes.item(0);
  Element rootElement = (Element) rootNode;
  NodeList templateList = rootElement.getElementsByTagName("template");

  for(int i=0; i < templateList.getLength(); i++) {
  Node theTemplate = templateList.item(i);
  Element templateElement = (Element) theTemplate;
  System.out.println("Template" + ": " +templateElement.getAttribute("name")+ ".xml");

  }
  } catch (ParserConfigurationException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
  } catch (SAXException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
  } catch (IOException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
  }

  }


}

1 个答案:

答案 0 :(得分:0)

像往常一样使用File I / O API在循环中创建xml文件。

// for every Node in the template List
for(int i=0; i < templateList.getLength(); i++) {

  // cast each Node to a template Element
  Node theTemplate = templateList.item(i);
  Element templateElement = (Element) theTemplate;

  // get the xml filename as = template's name attribute + .xml
  String fileName = templateElement.getAttribute("name") + ".xml";

  // create a Path that points to the current directory
  Path filePath = Paths.get(fileName);

  // create the xml file at the specified Path
  Files.createFile(filePath);

  System.out.println("File "+ fileName + ".xml created");
}

上面的代码将在您当前的工作目录中创建xml文件。您还需要处理已检查的IOException