JAVA XML PARSING TO SPLIT基于对象和类标记元素的XML

时间:2012-12-27 07:32:57

标签: java xml

这是我正在解析的JAVA XML ..

<objects>          
    <object>...<class>A /<class>...</object>
    <object>...<class>B</class>....</object>
    <object>...<class>A /<class>...</object>
</objects>

现在我使用以下代码将XML拆分为3个基于object标签的XML。

    DocumentBuilder builder = dbf.newDocumentBuilder();
    Document doc = builder.parse("xml");
    doc.getDocumentElement().normalize();

    TransformerFactory tranFactory = TransformerFactory.newInstance(); 
    Transformer aTransformer = tranFactory.newTransformer(); 

    NodeList list =(NodeList) doc.getElementsByTagName("object");
    System.out.println("XML SPLITED");

       for (int i=0; i<list.getLength(); i++){
           Node element = list.item(i).cloneNode(true);
       if(element.hasChildNodes()){
        Source src = new DOMSource(element); 
        FileOutputStream fs=new FileOutputStream("XML" + i + ".xml");
        Result dest = new StreamResult(fs);
        aTransformer.transform(src, dest);
        fs.close();
       }

我的要求是只获取带有类标记A的文件。所以我的输出只有2个XML。请发布你的答案。

2 个答案:

答案 0 :(得分:2)

使用您的示例,您可以这样做:

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
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 org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class XmlSplitting {
  private static final Logger logger = Logger.getLogger(XmlSplitting.class.getName());
  private static final String FILE_PATH = "./";

  private DocumentBuilder builder;
  private Transformer transformer;

  public XmlSplitting() throws ParserConfigurationException, TransformerConfigurationException {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    this.builder = factory.newDocumentBuilder();

    TransformerFactory transfromerFactory = TransformerFactory.newInstance();
    this.transformer = transfromerFactory.newTransformer();
  }

  public static void main(String[] args) {
    try {
      XmlSplitting s = new XmlSplitting();
      s.run();
    } catch (ParserConfigurationException | SAXException | IOException | TransformerException x) {
      logger.log(Level.SEVERE, "Error", x);
    }
  }

  private void run() throws ParserConfigurationException, SAXException, IOException, TransformerException {
    File file = new File(FILE_PATH + "xml.xml");
    if (file.exists()) {
      Document document = this.builder.parse(file);
      document.normalize();

      NodeList list = document.getElementsByTagName("object");
      for (int i = 0; i < list.getLength(); i++) {
        Node node = list.item(i);
        if (Node.ELEMENT_NODE == node.getNodeType()) {
          Element object = (Element)node;
          NodeList classes = object.getElementsByTagName("class");
          if (1 == classes.getLength()) {
            Node clazz = classes.item(0);
            if (Node.ELEMENT_NODE == clazz.getNodeType()) {
              this.copyNodeToNewFile(clazz.getTextContent(), node, i);
            }
          } else {
            logger.log(Level.SEVERE, "Number of class nodes in node object is different than expected. Number of class nodes found: {0}.", classes.getLength());
          }
        }
      }
    } else {
      logger.log(Level.SEVERE, "You provided wrong path for xml file.");
    }
  }

  private void copyNodeToNewFile(String content, Node node, int i) throws IOException, TransformerException {
    boolean copy = this.nodeShouldBeCopied(content);
    logger.log(Level.INFO, "Node with content {0} will {1}be moved to separete file.", new Object[]{content, true == copy ? "" : "not "});
    if (copy) {
      String fileName = String.format("%sxml%d.xml", FILE_PATH, i);
      try (FileOutputStream fos = new FileOutputStream(fileName)) {
        Source source = new DOMSource(node);
        Result destination = new StreamResult(fos);
        this.transformer.transform(source, destination);
      }
    }
  }

   // here you can change condition to copy given node to file
  private boolean nodeShouldBeCopied(String content) {
    return content.contains("A");
  }
}

答案 1 :(得分:-1)

如何使用巴西框架解析XML?它会让你的代码更具异国情调,你可以告诉你的朋友: http://jcoltrane.sourceforge.net/userguide/extending_parsing_process.html