
正文
java写入xml代码 java写入xml文件
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
如何用Java实现对xml文件的读取和写入以及保存
直接附源码import java.io.FileWriter;
import java.io.IOException;
import java.util.Iterator;import org.dom4j.*;
import org.dom4j.io.XMLWriter;
public class Dom4jSample { public static void main(String[] args) {
Dom4jSample dom4jSample = new Dom4jSample();
Document document = dom4jSample.createDocument();
try{
dom4jSample.FileWrite(document);
Document documentStr = dom4jSample.StringToXML("ChinaI Love!/China");
dom4jSample.XMLWrite(documentStr);
Element legend = dom4jSample.FindElement(document);
System.out.println(legend.getText());
}
catch(Exception e)
{
}
}
/*
* Create a XML Document
*/
public Document createDocument()
{
Document document = DocumentHelper.createDocument();
Element root = document.addElement("root");
Element author1 = root.addElement("Lynch");
author1.addAttribute("Age","25");
author1.addAttribute("Country","China");
author1.addText("I am great!");
Element author2 = root.addElement("Legend");
author2.addAttribute("Age","25");
author2.addAttribute("Country","China");
author2.addText("I am great!too!");
return document;
}
/*
* Create a XML document through String
*/
public Document StringToXML(String str) throws DocumentException
{
Document document = DocumentHelper.parseText(str);
return document;
}
public Element FindElement(Document document)
{
Element root = document.getRootElement();
Element legend = null;
for(Iterator i=root.elementIterator("legend");i.hasNext();)
{
legend = (Element)i.next();
}
return legend;
}
/*
* Write a XML file
*/
public void FileWrite(Document document) throws IOException
{
FileWriter out = new FileWriter("C:/Dom2jSample.xml");
document.write(out);
out.close();
}
/*
* Write a XML format file
*/
public void XMLWrite(Document document) throws IOException
{
XMLWriter writer = new XMLWriter(new FileWriter("C:/Dom2jSampleStr.xml"));
writer.write(document);
writer.close();
}
}
相关问答
Q1: java查询数据写入xml
先用ajax发送异步请求到一个servlet或action
然后用action调用查询数据方法返回数据之后对数据进行迭代写入xml然后返回一个null就行了.
action代码
//设置xml头
response.setContentType ("text/xml; charset=UTF-8");
//设置不缓存 response.setHeader("cache-control","no-cache");
try
{
out=response.getWriter();
}
catch (IOException e)
{
e.printStackTrace();
}
Iterator ite=(Iterator)user.selectList(count);
Sysuser sysUser=null;
//写入xml
out.println("root");
while(ite.hasNext())
{
sysUser=(Sysuser)ite.next();
out.println("sysUser");
out.println("username");
out.println(sysUser.getUsername());
out.println("/username");
out.println("role");
out.println(sysUser.getSysrole().getRoleName());
out.println("/role");
out.println("popedom");
out.println(sysUser.getSysrole().getPopedom());
out.println("/popedom");
out.println("/sysUser");
}
out.println("/root");
out.close();
return null;
javascript代码
//初始化xmlHttpRequest
function init()
{
try
{
xmlHttpRequest= new XMLHttpRequest();
}
catch(e1)
{
try
{
xmlHttpRequest=new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e)
{
xmlHttpRequest=new ActiveXObject("Microsoft.XMLHTTP");
}
}
}
//发送异步请求
function sendRequest()
{
init();
var url="/ManpowerResource/sysUserAjaxListAction.do?count="+count;
xmlHttpRequest.open('Get',url,true);
//设置回调函数
xmlHttpRequest.onreadystatechange=processRequest;
xmlHttpRequest.send(null);
}
//回调函数
function processRequest()
{
//判断返回状态 if(xmlHttpRequest.readyState==4)
{
if(xmlHttpRequest.status==200)
{
//获得返回的xml数据信息
var xmlDom=xmlHttpRequest.responseXML;
//前面定义的xml标签为:sysUser所以这里就获得sysUser这个节点
var sysUserDom=xmlDom.getElementsByTagName("sysUser");
//解析xml代码...........
for(var i=0;isysUserDom.length;i++)
{
.......
}
}
}
}
Q2: java如何向xml文件写入内容?
我以前学dom解析的时候写了一个小例子,你参考参考
package com.lhx.test;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Text;
public class Test {
public static void main(String[] args) {
DocumentBuilderFactory fct=DocumentBuilderFactory.newInstance();
try {
DocumentBuilder bui=fct.newDocumentBuilder();
Document doc=bui.newDocument();
Element ps=doc.createElement("persons");
Element p1=doc.createElement("person");
Element p2=doc.createElement("person");
Attr id1=doc.createAttribute("id");
Attr id2=doc.createAttribute("id");
id1.setNodeValue("1");
id2.setNodeValue("2");
Element name1=doc.createElement("name");
Text na1=doc.createTextNode("龙大哥");
Element name2=doc.createElement("name");
Text na2=doc.createTextNode("龙大爷");
Element sex1=doc.createElement("sex");
Text se1=doc.createTextNode("帅哥");
Element sex2=doc.createElement("sex");
Text se2=doc.createTextNode("妹子");
doc.appendChild(ps);
ps.appendChild(p1);
p1.appendChild(name1);
p1.setAttributeNode(id1);
name1.appendChild(na1);
p1.appendChild(sex1);
sex1.appendChild(se1);
ps.appendChild(p2);
p2.appendChild(name2);
p2.setAttributeNode(id2);
name2.appendChild(na2);
p2.appendChild(sex2);
sex2.appendChild(se2);
try {
FileOutputStream fos=new FileOutputStream(new File("E:/longdada.xml"));
try {
((org.apache.crimson.tree.XmlDocument)doc)
.write(fos);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
fos.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
附图:
这个例子有文本节点的创建,属性的创建等等,基本上可以解决绝大多数XML内容了。无论你想创建什么类型的XML,可以套用里面的方法。
另外,注意:文件通过流创建的时候用到一个类,需要一个jar,这个类我已经用完整形式写出来了,你去网上下载下来,添加进工程即可。
弱国觉得可行,望采纳^_^
Q3: JAVA如何写XML文件?
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\x0a Element 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\x0a Element 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\x0a try {\x0d\x0a OutputFormat format = new OutputFormat("\x0d\x0a ", true);\x0d\x0a format.setEncoding("gb2312");\x0d\x0a // 可以把System.out改为java写入xml代码你要java写入xml代码的流。\x0d\x0a XMLWriter xmlWriter = new XMLWriter(new PrintWriter(System.out), format);\x0d\x0a xmlWriter.write(doc);\x0d\x0a xmlWriter.close();\x0d\x0a } catch (IOException e) {\x0d\x0a e.printStackTrace();\x0d\x0a }\x0d\x0a }\x0d\x0a }
关于java写入xml代码和java写入xml文件的介绍到此就结束了,不知道你从中找到你需要的信息了吗 ?如果你还想了解更多这方面的信息,记得收藏关注本站。








