JAVA如何写XML文件?

JAVA如何写XML文件?,第1张

import java.io.*\x0d\x0a \x0d\x0aimport org.dom4j.*\x0d\x0a import org.dom4j.io.OutputFormat\x0d\x0a import org.dom4j.io.XMLWriter\x0d\x0a \x0d\x0apublic class DOM4JTest {\x0d\x0a public static void main(String[] args) {\x0d\x0a Document doc = DocumentHelper.createDocument()\x0d\x0a doc.addProcessingInstruction("xml-stylesheet", "type='text/xsl href='students.xsl'")\x0d\x0a Element root = doc.addElement("students")\x0d\x0a \x0d\x0aElement eltStu1 = root.addElement("student").addAttribute("sn", "01")\x0d\x0a Element eltName1 = eltStu1.addElement("name")\x0d\x0a Element eltAge1 = eltStu1.addElement("age")\x0d\x0a eltName1.setText("张三")\x0d\x0a eltAge1.setText("20")\x0d\x0a \x0d\x0aElement eltStu2 = root.addElement("student").addAttribute("sn", "02")\x0d\x0a Element eltName2 = eltStu2.addElement("name")\x0d\x0a Element eltAge2 = eltStu2.addElement("age")\x0d\x0a eltName2.setText("李四")\x0d\x0a eltAge2.setText("18")\x0d\x0a \x0d\x0atry {\x0d\x0aOutputFormat format = new OutputFormat("\x0d\x0a ", true)\x0d\x0aformat.setEncoding("gb2312")\x0d\x0a// 可以把System.out改为你要的流。\x0d\x0aXMLWriter xmlWriter = new XMLWriter(new PrintWriter(System.out), format)\x0d\x0axmlWriter.write(doc)\x0d\x0axmlWriter.close()\x0d\x0a } catch (IOException e) {\x0d\x0ae.printStackTrace()\x0d\x0a }\x0d\x0a }\x0d\x0a }

用java自带的就可以,有问题可以问我

import javax.xml.parsers.DocumentBuilder

import javax.xml.parsers.DocumentBuilderFactory

//构造

public XMLUtil(String name) throws ParserConfigurationException {

filename = name

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance()

builder = factory.newDocumentBuilder()

document = builder.newDocument()

}

/**

* 保存到文件

*/

public void toSave() {

try {

TransformerFactory tf = TransformerFactory.newInstance()

Transformer transformer = tf.newTransformer()

DOMSource source = new DOMSource(document)

transformer.setOutputProperty(OutputKeys.ENCODING, "GB2312")

transformer.setOutputProperty(OutputKeys.INDENT, "yes")

PrintWriter pw = new PrintWriter(new FileOutputStream(filename))

StreamResult result = new StreamResult(pw)

transformer.transform(source, result)

} catch (TransformerException mye) {

mye.printStackTrace()

} catch (IOException exp) {

exp.printStackTrace()

}

}


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/tougao/12013786.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-20
下一篇 2023-05-20

发表评论

登录后才能评论

评论列表(0条)

保存