1.加载xml文件:
首先生成一个docmentBuilder :
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
利用io流加载xml:
FileInputStream inputstream = new FileInputStream("f:/hk.xml");
Document doc=builder.parse(inputstream);
将xml转化为字符串:
TransformerFactory tf = TransformerFactory.newInstance();
Transformer t = tf.newTransformer();
t.setOutputProperty("encoding", "utf-8");//格式编码为utf-8
ByteArrayOutputStream bos = new ByteArrayOutputStream();
t.transform(new DOMSource(doc), new StreamResult(bos));
bos.toString();
2.创建xml文件:
首先生成一个docmentBuilder:
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
创建一个新的dom,添加根节点:
Document xmldoc = db.newDocument();
Element root=xmldoc.createElement("root");
. . . . . .
将Element对象转化为字符串:
仿照上面的 xml转化成字符串 只需将doc改成root.
更多推送文章请关注公众号: