基于对象和类标签元素的 JAVA XML 解析到分割 XML

标签 java xml

这是我正在解析的 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。请发布您的答案。

最佳答案

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

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");
  }
}

关于基于对象和类标签元素的 JAVA XML 解析到分割 XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14051093/

相关文章:

java - JDOM:将内容转换为文档

java - 从 ByteStream 创建 ZIP/TGZ 存档

java - 求最长不包含重复字符的子串的长度

java - 在Java中如何使溢出文本转到下一行

Java库函数将任意字符串转换为XML ID

c# - 从 xml 文档解码 base64 编码的数据

java - 来自 InputStream 的编年史字节

java - 如何管理远程java程序?

xml - 使用 powershell 更新 xml 元素

xml - 是数字,在 XPath 或 XSL 中是字母/数字