0

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

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

现在我使用下面的代码将 XML 拆分为基于对象标记的 3 个 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。请发布您的答案。

4

2 回答 2

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");
  }
}
于 2012-12-27T11:43:44.613 回答
-1

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

于 2012-12-27T11:51:53.420 回答