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

How do I create individual XML files from the parsed data output of a XML file?

我编写了一个程序(DOM 解析器)来解析来自 XMl 文件的数据。我想为从 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();
  }

  }


}

只需像往常一样使用文件 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