A. java怎样读写和修改XML文件
xml:
<?xml version="1.0" encoding="UTF-8"?>
<users>
<Messages>
<sendName>sendUsers</sendName>
<receiveName>snake</receiveName>
<date>2007-12-04 12:20:00</date>
<status>0</status>
<message>this is Content</message>
</Messages>
</users>
java:
package com.lianxi.DAO;
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
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;
import org.w3c.dom.NodeList;
public class UpdateXml {
public static boolean doc2XmlFile(Document document,String filename)
{
boolean flag = true;
try
{
/** 将document中的内容写入文件中 */
TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer transformer = tFactory.newTransformer();
/** 编码 */
//transformer.setOutputProperty(OutputKeys.ENCODING, "GB2312");
DOMSource source = new DOMSource(document);
StreamResult result = new StreamResult(new File(filename));
transformer.transform(source, result);
}catch(Exception ex)
{
flag = false;
ex.printStackTrace();
}
return flag;
}
public static Document load(String filename)
{
Document document = null;
try
{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder=factory.newDocumentBuilder();
document=builder.parse(new File(filename));
document.normalize();
}
catch (Exception ex){
ex.printStackTrace();
}
return document;
}
/**
* 演示修改文件的具体某个节点的值
*/
public static void xmlUpdateDemo()
{
Document document = load("c://Message.xml");
Node root=document.getDocumentElement();
/** 如果root有子元素 */
if(root.hasChildNodes())
{
/** ftpnodes */
NodeList ftpnodes = root.getChildNodes();
/** 循环取得ftp所有节点 */
for (int i=0;i<ftpnodes.getLength();i++)
{
NodeList ftplist = ftpnodes.item(i).getChildNodes();
for (int k=0;k<ftplist.getLength();k++)
{
Node subnode = ftplist.item(k);
/** 删除ftp-chn节点 */
// if (subnode.getNodeType()==Node.ELEMENT_NODE&&subnode.getNodeName()=="ftp-chn")
// {
// ftpnodes.item(i).removeChild(subnode);
// }
/** 修改ftp-host的值为 192.168.0.1 */
if (subnode.getNodeType()==Node.ELEMENT_NODE&&subnode.getNodeName()=="status")
{
subnode.getFirstChild().setNodeValue("1");
}
}
}
}
doc2XmlFile(document,"c://Message.xml");
}
public static void main(String args[])throws Exception
{
UpdateXml.xmlUpdateDemo();
}
}
B. java如何还原xml中的转义字符
忽略转义的工具类, org.apache.commons.lang.StringEscapeUtils,其中unescapeJava(String s)方法是来处理java转义字符的,可以将字符串中的 “\”转换为 “\”,“'”转换为“'”等。通过这个方法处理以上字符串
public class Test(){ public static void main(String[] args) { String s = "\\u79fb\\u52a8\\u4e92\\u8054\\u7f51\\u5e94\\u7528"; String s2 = StringEscapeUtils.unescapeJava(s); System.out.println(s); System.out.println(s2); } }
输出结果: \u79fb\u52a8\u4e92\u8054\u7f51\u5e94\u7528移动互联网应用
C. 如何把xml内容转换为java格式
使用XStream完成 java 类与 XML 互换。
下面代码实现了以下4种基本功能:
1. object类型转换为xml类型,在控制台打印
2. xml类型转换为object类型,在控制台打印
3. 将object类型转换为xml类型,并写入XML文件
4. 读取XML文件,加载进相应Object类型
====================================================
1。加载 XStream 需要的jar包 xstream-1.4.2.jar
xpp3_min-1.1.4c.jar
xmlpull-1.1.3.1.jar
2。创建实体类User.java
package com.entity;
/**
* 实体类
*/
public class User {
private String userName;
private String passWord;
private String registeredTime;
public User() { }
public User(String userName, String passWord, String registeredTime) {
this.userName = userName;
this.passWord = passWord;
this.registeredTime = registeredTime;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassWord() {
return passWord;
}
public void setPassWord(String passWord) {
this.passWord = passWord;
}
public String getRegisteredTime() {
return registeredTime;
}
public void setRegisteredTime(String registeredTime) {
this.registeredTime = registeredTime;
}
}
3。编写功能实现类
package com.switcher;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import com.entity.User;
import com.thoughtworks.xstream.XStream;
/**
*
* 使用 XStream不用任何映射就能实现多数 Java 对象的序列化。
* 在生成的 XML中对象名变成了元素名,类中的字符串组成了 XML中的元素内容。
* 使用 XStream 序列化的类不需要实现 Serializable 接口。
* XStream 是一种序列化工具而不是数据绑定工具
* 不能从XML 或者 XML Schema Definition (XSD) 文件生成类。
*/
public class SwitchXML {
/*
* XStream 不关心序列化/逆序列化的类的字段的可见性。
* 序列化/逆序列化类的字段不需要 getter 和 setter 方法。
* 序列化/逆序列化的类不需要有默认构造函数。
*/
private XStream xStream = new XStream();
private String xmlPath = "D:/userdata.xml";
// 1. obj -> xml(object类型转换为xml类型)
public String printXML(User user) {
System.out.println("obj -> xml");
String xml = xStream.toXML(user);
System.out.println(xml);
return xml;
}
// 2. xml->obj(xml类型转换为object类型,并打印)
public void printObj(String xml) {
System.out.println("xml -> obj");
User u = (User) xStream.fromXML(xml);
System.out.println(u.getUserName() + " " + u.getPassWord() + " " + u.getRegisteredTime());
}
// 3. 将object类型转换为xml类型,并写入XML文件(其他格式也可以,比如txt文件)
public void writerXML(User user) {
try {
FileOutputStream fs = new FileOutputStream(xmlPath);
xStream.toXML(user, fs);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
// 4. 读取XML文件,加载进相应Object类型
public void readerXML() {
User user = new User();
FileInputStream fis = null;
try {
fis = new FileInputStream(xmlPath);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
xStream.fromXML(fis, user);
// 打印对象信息
System.out.println(user.toString());
// 打印对象的属性值
System.out.println(user.getUserName() + "-" + user.getPassWord() + "-"
+ user.getRegisteredTime());
}
public static void main(String[] args) {
// 用户名
String username = "admin";
// 密码
String password = "admin";
// 注册时间
Date now = new Date();
SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
String registeredtime = format.format(now);
User user = new User(username, password, registeredtime);
SwitchXML switchXML = new SwitchXML();
// 1. object类型转换为xml类型,在控制台打印
String xml = switchXML.printXML(user);
System.out.println("---------------------");
// 2. xml类型转换为object类型,在控制台打印
switchXML.printObj(xml);
System.out.println("---------------------");
// 3. 将object类型转换为xml类型,并写入XML文件
switchXML.writerXML(user);
System.out.println("---------------------");
// 4. 读取XML文件,加载进相应Object类型
switchXML.readerXML();
}
}
D. 怎么使用java导出大数据为xml文件
dom4j可以试试,不知道你的数据量有多大,如果太大的话,我没试过
xml文件是有规律的,你可以把要导出的数据构造一下,
我有个简单的代码
packagecom.test.xml;
importjava.io.FileWriter;
importjava.io.IOException;
importjava.io.Writer;
importorg.dom4j.Document;
importorg.dom4j.DocumentHelper;
importorg.dom4j.Element;
importorg.dom4j.io.OutputFormat;
importorg.dom4j.io.XMLWriter;
publicclassDom4JXML{
publicvoidcreateXML(){
//用工厂类创建一个document实例
Documentdoc=DocumentHelper.createDocument();
//创建根元素emps
ElementrootEle=doc.addElement("emps");
//添加注释
rootEle.addComment("这是一个dom4j生成的xml文件");
//emps根节点下创建一个emp节点
ElementempEle=rootEle.addElement("emp");
//emp添加属性id="1"
empEle.addAttribute("id","1");
//emp节点下创建一个name节点
ElementnameEle=empEle.addElement("name");
//name节点下创建一个文本节点zhangsan
nameEle.setText("zhangsan");
//再为name节点创建一个兄弟节点
ElementsexEle=empEle.addElement("sex");
sexEle.setText("man");
//将document中的内容写入文件中
try{
Writerout=newFileWriter("F:\emps.xml");
//格式化输出,类型IE浏览一样
OutputFormatformat=OutputFormat.createPrettyPrint();
//OutputFormatformat=OutputFormat.createCompactFormat();
format.setEncoding("UTF-8");
//创建写出对象
XMLWriterwriter=newXMLWriter(out,format);
writer.write(doc);
writer.close();
System.out.println("生成emps.xml成功。");
}catch(IOExceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
System.out.println("失败了。");
}
}
publicstaticvoidmain(String[]args){
newDom4JXML().createXML();
}
}
然而从xml文件中解析以后的数据收集可以用SAX试试看
我这里有个简单的例子
packagecom.test.xml;
importorg.xml.sax.Attributes;
importorg.xml.sax.SAXException;
importorg.xml.sax.helpers.DefaultHandler;
{
publicvoidstartDocument()throwsSAXException{
System.out.println("起始文挡");
}
publicvoidendDocument()throwsSAXException{
System.out.println("结束文挡");
}
publicvoidcharacters(char[]ch,intstart,intlength)throwsSAXException{
StringcharString=newString(ch,start,length);
System.out.println("字符:"+charString);
}
publicvoidstartElement(StringnamespaceURI,StringlocalName,StringqName,Attributesatts)throwsSAXException{
System.out.println("起始元素:"+qName);
for(inti=0;i<atts.getLength();i++){
System.out.println("属性值:"+atts.getValue(i));
}
}
publicvoidendElement(StringnamespaceURI,StringlocalName,StringqName)throwsSAXException{
System.out.println("结束元素:"+qName);
}
}
packagecom.test.xml;
importjavax.xml.parsers.SAXParser;
importjavax.xml.parsers.SAXParserFactory;
publicclassBooks{
/**
*@paramargs
*/
publicstaticvoidmain(String[]args)throwsException{
//TODO自动生成方法存根
SAXParserFactoryfactory=SAXParserFactory.newInstance();
SAXParserparser=factory.newSAXParser();
parser.parse("booksamp.xml",newSAXParseHandler());
}
}
E. JAVA如何写XML文件
呵呵,你这个问题,其实写XML很简单的,氛围以下几步:
1.导入DOM4J包,在此我使用dom4j来做。
2.创建dom4j的实例:Document document = DocumentHelper.createDocument();
3.一级一级的添加节点或者属性,这个具体参照dom4j帮助:
Element rootGen = document.addElement("root");
4.定义以下3个对象,然后进行操作:
Writer writer = null;
OutputFormat format = null;
XMLWriter xmlwriter = null;
***********************************************************************************
附上代码:
public void CreateXMl(StudentBean sn){
//创建document对象
Document document = DocumentHelper.createDocument();
//定义根节点Element
Element rootGen = document.addElement("root");
//定义根节点ROOT的子节点们
Element nameGen = rootGen.addElement("Name");
nameGen.addAttribute("name", "我是中文");
Element ageGen = rootGen.addElement("Age");
Element addrGen = rootGen.addElement("Address");
Writer writer = null;
OutputFormat format = null;
XMLWriter xmlwriter = null;
//将定义好的内容写入xml文件中
try {
//使用这个writer也可以,只不过遇到中文会乱码哦
// writer = new FileWriter("d:/test.xml");
//进行格式化
format = OutputFormat.createPrettyPrint();
//设定编码
format.setEncoding("UTF-8");
xmlwriter = new XMLWriter(new FileOutputStream("d:/test.xml"), format);
xmlwriter.write(document);
xmlwriter.flush();
xmlwriter.close();
System.out.println("-----------Xmlfile successfully created-------------");
} catch (Exception e) {
e.printStackTrace();
System.out.println("-----------Exception occured ring of create xmlfile -------");
}
}
F. 用Java怎么把String类型的字符串转化为XML格式输出
JXmlSerializable 是一个利用java反射,通过调用对象中所有以get(不区分大小写)开头的方法除去getClass方法,生成xml格式,希望与大家分享一下
下面是一个parent对象,包含两个child对象 生成的xml如下
Child类
1package xmlTest;
2
3import java.io.FileNotFoundException;
4import java.io.IOException;
5import java.io.PrintWriter;
6import java.lang.reflect.InvocationTargetException;
7public class Child extends JXmlSerializable {
8
9 private String _name;
10 private String _sex;
11 private int age;
12
13 public void setAge(int num) {
14 age = num;
15 }
16
17 public int getAge() {
18 return age;
19 }
20
21 public void setName(String name) {
22 _name = name;
23 }
24
25 public void setSex(String sex) {
26 _sex = sex;
27 }
28
29 public String getName() {
30 return _name;
31 }
32
33 public String getSex() {
34 return _sex;
35 }
36
37}
38
Parent类 1package xmlTest;
2
3import java.io.PrintWriter;
4import java.lang.reflect.Array;
5import java.util.*;
6
7public class Parent extends JXmlSerializable {
8
9 private String _name;
10 private String _sex;
11 private LinkedList list = new LinkedList();
12 private Vector vec = new Vector();
13 int age;
14
15 public void setAge(int num) {
16 age = num;
17 }
18
19 public int getAge() {
20 return age;
21 }
22
23 public void setName(String name) {
24 _name = name;
25 }
26
27 public void setSex(String sex) {
28 _sex = sex;
29 }
30
31 public String getName() {
32 return _name;
33 }
34
35 public String getSex() {
36 return _sex;
37 }
38
39 public void addChild(Child child) {
40 list.add(child);
41 vec.add(child);
42 }
43
44 public Child[] getChild() {
45
46 Child[] aa = new Child[vec.size()];
47 // list.toArray(aa);
48 vec.toArray(aa);
49 return aa;
50 }
51
52 public static void main(String[] args) {
53 // TODO Auto-generated method stub
54 try {
55 Parent pat = new Parent();
56 pat.setName("jack");
57 pat.setSex("male");
58 Child child1 = new Child();
59 child1.setName("tom");
60 child1.setSex("male");
61 pat.addChild(child1);
62 Child child2 = new Child();
63 child2.setName("Marie");
64 child2.setSex("female");
65 pat.addChild(child2);
66 pat.getChild();
67 PrintWriter out = new PrintWriter("abc.xml");
68 pat.toXmlSerial(out,0);
69 out.flush();
70
71 } catch (Exception e) {
72 e.printStackTrace();
73 }
74
75 }
76}
类 JXmlSerializable
1package xmlTest;
2
3import java.lang.reflect.Method;
4import java.lang.reflect.InvocationTargetException;
5import java.lang.reflect.Array;
6import java.io.PrintWriter;
7import java.io.IOException;
8public class JXmlSerializable {
9
10 public void toXmlSerial(PrintWriter out, int num)
11 throws InvocationTargetException, IllegalAccessException,
12 IOException {
13 out.write("<?xml version="1.0"?> ");
14 String head = "";
15 for (int i = 0; i < num; i++) {
16 head += " ";
17 }
18 out.write(head + "<" + this.getClass().getName() + "> ");
19 Method[] methods = this.getClass().getMethods();
20 for (int i = 0; i < methods.length; i++) {
21 Class[] paras = methods[i].getParameterTypes();
22 String name = methods[i].getName();
23 if (paras == null || paras.length == 0) {
24 if ((name.substring(0, 3).toLowerCase().equals("get"))
25 && !name.equals("getClass")) {
26 Object obj = methods[i].invoke(this, null);
27 getMethodXmlSerial(out, obj, methods[i], num);
28 }
29 }
30 }
31
32 out.write(head + "</" + this.getClass().getName() + "> ");
33
34 }
35
36 private void getMethodXmlSerial(PrintWriter out, Object obj, Method method,
37 int num) throws InvocationTargetException, IllegalAccessException,
38 IOException {
39 if (obj == null)
40 return;
41 String head = "";
42 for (int i = 0; i <= num; i++) {
43 head += " ";
44 }
45 if (obj.getClass().isArray()) {
46 for (int i = 0; i < Array.getLength(obj); i++) {
47 Object childobj = Array.get(obj, i);
48 if (childobj instanceof JXmlSerializable) {
49 ((JXmlSerializable) childobj).toXmlSerial(out, num + 1);
50 } else {
51 getMethodXmlSerial(out, childobj, method, num);
52 }
53 }
54 } else {
55 out.write(head + " <" + method.getName().substring(3) + "> ");
56 out.write(obj.toString());
57 out.write(" </" + method.getName().substring(3) + "> ");
58 }
59
60 }
61}
编译出来还可以,能够达到我的理想。
编译结果是
1<?xml version="1.0"?>
2<xmlTest.Parent>
3 <Name> jack </Name>
4 <Age> 0 </Age>
5 <Sex> male </Sex>
6<?xml version="1.0"?>
7 <xmlTest.Child>
8 <Name> tom </Name>
9 <Age> 0 </Age>
10 <Sex> male </Sex>
11 </xmlTest.Child>
12<?xml version="1.0"?>
13 <xmlTest.Child>
14 <Name> Marie </Name>
15 <Age> 0 </Age>
16 <Sex> female </Sex>
17 </xmlTest.Child>
18</xmlTest.Parent>
今天看了看java.beans包,发现了两个好东西,XMLEncoder和XMLDecoder。发现自己以前把从XML存取对象真是太费力气啦。做了小工具类,以后可以用用了。
1以下是引用片段:
2package com.imct.util;
3import java.beans.XMLDecoder;
4import java.beans.XMLEncoder;
5import java.io.File;
6import java.io.FileInputStream;
7import java.io.FileNotFoundException;
8import java.io.FileOutputStream;
9import java.io.IOException;
10import java.util.ArrayList;
11import java.util.List;
12/** *//**
13 * <title>使用XML文件存取可序列化的对象的类</title>
14 * <description>提供保存和读取的方法</description>
15 * @author 殷晋
16 * <right>清华大学汽车工程开发研究院@2005</right>
17 * @version 1.0
18 * 2005-8-5 16:44:49
19 */
20public class ObjectToXMLUtil
21{
22 /** *//**
23 * 把java的可序列化的对象(实现Serializable接口)序列化保存到XML文件里面,如果想一次保存多个可序列化对象请用集合进行封装
24 * 保存时将会用现在的对象原来的XML文件内容
25 * @param obj 要序列化的可序列化的对象
26 * @param fileName 带完全的保存路径的文件名
27 * @throws FileNotFoundException 指定位置的文件不存在
28 * @throws IOException 输出时发生异常
29 * @throws Exception 其他运行时异常
30 */
31 public static void objectXmlEncoder(Object obj,String fileName)
32 throws FileNotFoundException,IOException,Exception
33 {
34 //创建输出文件
35 File fo = new File(fileName);
36 //文件不存在,就创建该文件
37 if(!fo.exists())
38 {
39 //先创建文件的目录
40 String path = fileName.substring(0,fileName.lastIndexOf('.'));
41 File pFile = new File(path);
42 pFile.mkdirs();
43 }
44 //创建文件输出流
45 FileOutputStream fos = new FileOutputStream(fo);
46 //创建XML文件对象输出类实例
47 XMLEncoder encoder = new XMLEncoder(fos);
48 //对象序列化输出到XML文件
49 encoder.writeObject(obj);
50 encoder.flush();
51 //关闭序列化工具
52 encoder.close();
53 //关闭输出流
54 fos.close();
55 }
56 /** *//**
57 * 读取由objSource指定的XML文件中的序列化保存的对象,返回的结果经过了List封装
58 * @param objSource 带全部文件路径的文件全名
59 * @return 由XML文件里面保存的对象构成的List列表(可能是一个或者多个的序列化保存的对象)
60 * @throws FileNotFoundException 指定的对象读取资源不存在
61 * @throws IOException 读取发生错误
62 * @throws Exception 其他运行时异常发生
63 */
64 public static List objectXmlDecoder(String objSource)
65 throws FileNotFoundException,IOException,Exception
66 {
67 List objList = new ArrayList();
68 File fin = new File(objSource);
69 FileInputStream fis = new FileInputStream(fin);
70 XMLDecoder decoder = new XMLDecoder(fis);
71 Object obj = null;
72 try
73 {
74 while( (obj = decoder.readObject()) != null)
75 {
76 objList.add(obj);
77 }
78 }
79 catch (Exception e)
80 {
81 // TODO Auto-generated catch block
82 }
83 fis.close();
84 decoder.close();
85 return objList;
86 }
87}
88
89
90当然用Beans.instantiate也可以从文件中反序列化初对象
G. 如何用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("<China>I 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();
}
}
H. 使用java如何修改某个xml文件中的某项内容
代码如下:
import org.jdom.*;
import org.jdom.output.*;
import org.jdom.input.*;
import java.io.*;
public class xml{
public void toXml() throws JDOMException,IOException{
SAXBuilder saxBuilder=new SAXBuilder(false);
saxBuilder.setExpandEntities(false);
File file = new File("c:\\test.xml");
Document doc =saxBuilder.build(new File("c:\\test.xml"));
Element elem=doc.getRootElement();
//System.out.println(elem.toString());
elem.getChild("Collectors").getChild("Collector"手握).getAttribute("败茄HostIP").setValue("192.168.0.1");
elem.getChild("Collectors").getChild("Collector").getAttribute("PortID").setValue("100000");
Element elem1 = (Element)elem.clone();
Document Doc=new Document(elem1);
XMLOutputter XMLOut = new XMLOutputter();
XMLOut.setEncoding("毕枯庆BIG5");
XMLOut.setNewlines(true);
file.delete();
XMLOut.output(Doc,new FileOutputStream("c:\\test"+".xml"));
}
public static void main(String args[]){
xml x = new xml();
try{
x.toXml();
}catch(Exception e){}
}
}