App下載
首頁javadomJava HTML/XML - 如何將XML節(jié)點轉(zhuǎn)換為字符串

Java HTML/XML - 如何將XML節(jié)點轉(zhuǎn)換為字符串

我們想知道如何將XML節(jié)點轉(zhuǎn)換為字符串。
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.StringWriter;

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

public class Main {
  public static void main(String[] args) throws Exception {
    String s = 
      "<p>" +
      "  <media type='audio' id='au008093' rights='aaa'>" +
      "    <title>title</title>" +
      "  this is a test." +
      "</p>";
    InputStream is = new ByteArrayInputStream(s.getBytes());

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document d = db.parse(is);

    Node rootElement = d.getDocumentElement();
    System.out.println(nodeToString(rootElement));
  }
  private static String nodeToString(Node node) throws Exception{
    StringWriter sw = new StringWriter();

      Transformer t = TransformerFactory.newInstance().newTransformer();
      t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
      t.setOutputProperty(OutputKeys.INDENT, "yes");
      t.transform(new DOMSource(node), new StreamResult(sw));

    return sw.toString();
  }
}