App下載
首頁javadomJava HTML/XML - 如何將子元素從XML提取到字符串

Java HTML/XML - 如何將子元素從XML提取到字符串

我們想知道如何將子元素從XML提取到字符串。
import java.io.File;
import java.io.StringWriter;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
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;

public class Main {
  public static void main(String[] args) throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse(new File("in.xml"));

    TransformerFactory tFactory = TransformerFactory.newInstance();
    Transformer transformer = tFactory.newTransformer();
    transformer.setOutputProperty("indent", "yes");
    StringWriter sw = new StringWriter();
    StreamResult result = new StreamResult(sw);

    NodeList nl = doc.getDocumentElement().getChildNodes();
    DOMSource source = null;
    for (int x = 0; x < nl.getLength(); x++) {
      Node e = nl.item(x);
      if (e instanceof Element) {
        source = new DOMSource(e);
        break;
      }
    }
    transformer.transform(source, result);
    System.out.println(sw.toString());
  }
}