不借助第三方类库,使用JDK自带API操作XML

先放2个主要方法:

import java.io.StringReader;
import java.io.StringWriter;

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

public class Test {
	
	public String domToString(Document doc) throws Exception {
		Transformer tf = TransformerFactory.newInstance().newTransformer();
		StringWriter sw = new StringWriter();
		Source source = new DOMSource(doc);
		tf.transform(source, new StreamResult(sw));
		return sw.toString();
	}
	
	public Document stringToDom(String xml) throws Exception {
		DocumentBuilder db = DocumentBuilderFactory
		.newInstance().newDocumentBuilder();
		InputSource is = new InputSource(new StringReader(xml));
		return db.parse(is);
	}
}




你可能感兴趣的:(不借助第三方类库,使用JDK自带API操作XML)