这是读取xml文件的java程序,我调试好的。采用的是dom方式读取xml文件到Vector中。
package src;
import java.io.*;
import java.util.Vector;
import javax.xml.parsers.*;
import org.w3c.dom.*;
public class readxml {
static Document document;
private boolean validating;
public readxml() {
}
public Vector toRead(String filename) {
Vector title=new Vector();
Vector content=new Vector();
String myStr=new String();
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(validating);
DocumentBuilder builder = factory.newDocumentBuilder();
document = builder.parse(new File(filename));
document.getDocumentElement().normalize();
Node node = document.getFirstChild();
NodeList list = node.getChildNodes();
for (int i = 0; i < list.getLength(); i++) {
Node nodeitm = list.item(i);
if (nodeitm.getNodeName().equals("Title")) {
myStr=nodeitm.getFirstChild().getNodeValue();
title.addElement(myStr);//getFirstChild()
}
if (nodeitm.getNodeName().equals("Content")) {
myStr=nodeitm.getFirstChild().getNodeValue();
content.addElement(myStr);
}
}
} catch (Exception exp) {
exp.printStackTrace();
return null;
}
Vector all=new Vector();
all.add(title);
all.add(content);
return all;
} public static void main(String[] args) {
Vector A;
readxml my = new readxml();
A = my.toRead("f:\\tomcat5\\webapps\\myxml\\xmldata\\9.xml");
for (int i = 0; i < A.size(); i++) {
System.out.println(A.elementAt(i));
}
}
}
这是将xml写入文件。其中,transformer.setOutputProperty(OutputKeys.ENCODING,"GB2312")关系到编码问题,非常重要。
import org.w3c.dom.*;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.*;
public class writexml {
private Document document;
private String filename; public writexml(String name) throws ParserConfigurationException{
filename=name;
DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
DocumentBuilder builder=factory.newDocumentBuilder();
document=builder.newDocument();
}
public void toWrite(String mytitle,String mycontent){
Element root=document.createElement("WorkShop");
document.appendChild(root);
Element title=document.createElement("Title");
title.appendChild(document.createTextNode(mytitle));
root.appendChild(title);
Element content=document.createElement("Content");
content.appendChild(document.createTextNode(mycontent));
root.appendChild(content);
}
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();
}
}
public static void main(String args[]){
try{
writexml myxml=new writexml("f:\\tomcat5\\webapps\\myxml\\xmldata\\9.xml");
myxml.toWrite("中文题目","中文内容");
myxml.toSave();
System.out.print("Your writing is successful.");
}
catch(ParserConfigurationException exp){
exp.printStackTrace();
System.out.print("Your writing is failed.");
}
}
}
package src;
import java.io.*;
import java.util.Vector;
import javax.xml.parsers.*;
import org.w3c.dom.*;
public class readxml {
static Document document;
private boolean validating;
public readxml() {
}
public Vector toRead(String filename) {
Vector title=new Vector();
Vector content=new Vector();
String myStr=new String();
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(validating);
DocumentBuilder builder = factory.newDocumentBuilder();
document = builder.parse(new File(filename));
document.getDocumentElement().normalize();
Node node = document.getFirstChild();
NodeList list = node.getChildNodes();
for (int i = 0; i < list.getLength(); i++) {
Node nodeitm = list.item(i);
if (nodeitm.getNodeName().equals("Title")) {
myStr=nodeitm.getFirstChild().getNodeValue();
title.addElement(myStr);//getFirstChild()
}
if (nodeitm.getNodeName().equals("Content")) {
myStr=nodeitm.getFirstChild().getNodeValue();
content.addElement(myStr);
}
}
} catch (Exception exp) {
exp.printStackTrace();
return null;
}
Vector all=new Vector();
all.add(title);
all.add(content);
return all;
} public static void main(String[] args) {
Vector A;
readxml my = new readxml();
A = my.toRead("f:\\tomcat5\\webapps\\myxml\\xmldata\\9.xml");
for (int i = 0; i < A.size(); i++) {
System.out.println(A.elementAt(i));
}
}
}
这是将xml写入文件。其中,transformer.setOutputProperty(OutputKeys.ENCODING,"GB2312")关系到编码问题,非常重要。
import org.w3c.dom.*;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.*;
public class writexml {
private Document document;
private String filename; public writexml(String name) throws ParserConfigurationException{
filename=name;
DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
DocumentBuilder builder=factory.newDocumentBuilder();
document=builder.newDocument();
}
public void toWrite(String mytitle,String mycontent){
Element root=document.createElement("WorkShop");
document.appendChild(root);
Element title=document.createElement("Title");
title.appendChild(document.createTextNode(mytitle));
root.appendChild(title);
Element content=document.createElement("Content");
content.appendChild(document.createTextNode(mycontent));
root.appendChild(content);
}
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();
}
}
public static void main(String args[]){
try{
writexml myxml=new writexml("f:\\tomcat5\\webapps\\myxml\\xmldata\\9.xml");
myxml.toWrite("中文题目","中文内容");
myxml.toSave();
System.out.print("Your writing is successful.");
}
catch(ParserConfigurationException exp){
exp.printStackTrace();
System.out.print("Your writing is failed.");
}
}
}
解决方案 »
- cmd运行java不行
- spring 利用security 登陆 session 重复创建的问题(高分求助)
- <input type="button 和 <button 的区别
- 使用lomboz插件后无法运行jsp
- 谁能提供工作流shark jawe 相关资料
- Tomcat 必需JDK吗?JRE是否可以?
- 【我在webapps下面放了一个一般的文件夹(里面不含jsp,html),我应该怎么访问这个文件啊?】
- 选择jsp和java,困惑,请大家指教!
- 在struts中怎么样实现选项卡(tab)的功能
- 一个很有哲理的问题
- 学j2ee(jms,rmi,ejb这类东西,不是普通做网站用的jsp)哪个网站或论坛比较好
- 本人想出一本ant的书,大家有什么意见
import org.jdom.input.*;
import org.jdom.output.*;
import java.util.*;
import java.io.*;public class SeachXml{ /***********************************************************
** getdoc **
********* 利用开源包jdom解释XML文件 *********** ************************************************************/
public Document getdoc(){
Document doc=null;
PrintStream out=System.out;
try{
SAXBuilder builder=new SAXBuilder();
doc=builder.build("/*filename--xml文件名*/");
}catch(Exception e){
out.println("Exception:"+e.toString());
}
return doc;
}
/**************************************************************
**** insert ****
********* XML文件中插入节点 **************************************************************************/
public void insert(String name,String address,String fare,String content,String nodename,String nodeaddress,String nodefare,String nodecontent){
Document doc=getdoc();
if(doc!=null)
{
Element root=doc.getRootElement();
List list=root.getChildren(); Element newE=new Element("tour"); Element eName=new Element("name");
eName.setText(name);
newE.addContent(eName); Element eAddress=new Element("address");
eAddress.setText(address);
newE.addContent(eAddress); Element eFare=new Element("fare");
eFare.setText(fare);
newE.addContent(eFare); Element eContent=new Element("content");
eContent.setText(content);
newE.addContent(eContent); Element newEE=new Element("tournode");
Element eNodeName=new Element("nodaneme");
eNodeName.setText(nodename);
newEE.addContent(eNodeName); Element eNodeAddress=new Element("nodeaddress");
eNodeAddress.setText(nodeaddress);
newEE.addContent(eNodeAddress); Element eNodeFare=new Element("nodefare");
eNodeFare.setText(nodefare);
newEE.addContent(eNodeFare); Element eNodeContent=new Element("nodecontent");
eNodeContent.setText(nodecontent);
newEE.addContent(eNodeContent); newE.addContent(newEE);
root.addContent(newE); save(doc);
}
}/**************************************************************
**** delete ****
********* XML文件中删除节点 **************************************************************************/
public void delete(String str){
Document doc=getdoc();
if(doc!=null)
{
Element root=doc.getRootElement(); List list=root.getChildren();
Iterator list_i=list.iterator(); while(list_i.hasNext()){ Element e=(Element)list_i.next();
List details=e.getChildren(); String text=((Element)details.get(0)).getText();
System.out.println(text); if(!text.equals(str))
{
continue;
}
else
{
root.removeContent(e);
break;
}
}
}
save(doc);
}
/******
读取
*******/
public void read(){ Document doc=getdoc();
if(doc!=null)
{
List list;
Element root=doc.getRootElement(); list=root.getChildren();
Iterator list_i=list.iterator();
Element seachNode=null; while(list_i.hasNext()){
Element e=(Element)list_i.next();
Iterator list_ii=e.getChildren().iterator(); while(list_ii.hasNext()){ Element ee=(Element)list_ii.next();
String stee=ee.getText();
System.out.println(stee);
Iterator list_iii=ee.getChildren().iterator(); while(list_iii.hasNext()){
Element eee=(Element)list_iii.next();
String steee=eee.getText();
System.out.println(steee);
}
}
}
} }
//程序测试入口
public static void main(String args[]){
SeachXml rx=new SeachXml();
rx.read();
//rx.insert("象山公园","象山公园地处市中心的漓江与桃花江汇流处","20RMB","园内自然山水与人文景观相辉映。象山,栩栩如生,引人入胜,被人们称为桂林山水的象征。","象鼻山","象鼻山 位于市内桃花江与漓江汇流处","0RMB","是桂林名山之一, 主要景点有水月洞、象眼岩、普贤塔、宏峰寺及寺内的太平天国革命遗址陈列馆等。附近还有隋唐开元寺仅存的舍利塔。水月洞紧靠江边, 漓水流贯其间, 如水中浮月,山石垂入水中又如象鼻饮水漓江, 景致极佳, 唐宋以来即为游览胜地。宋蓟北处士《和水月洞韵》诗: 水底有明月, 水上明月浮。水流月不去, 月去水还流。形象地描绘了这一景致。");
// rx.delete("象山公园");
//rx.modify("象山公园","2象山公园地处市中心的漓江与桃花江汇流处","320RMB","4园内自然山水与人文景观相辉映。象山,栩栩如生,引人入胜,被人们称为桂林山水的象征。","5象鼻山","6象鼻山 位于市内桃花江与漓江汇流处","70RMB","8是桂林名山之一, 主要景点有水月洞、象眼岩、普贤塔、宏峰寺及寺内的太平天国革命遗址陈列馆等。附近还有隋唐开元寺仅存的舍利塔。水月洞紧靠江边, 漓水流贯其间, 如水中浮月,山石垂入水中又如象鼻饮水漓江, 景致极佳, 唐宋以来即为游览胜地。宋蓟北处士《和水月洞韵》诗: 水底有明月, 水上明月浮。水流月不去, 月去水还流。形象地描绘了这一景致。");
}
}