import org.jdom.*;
import org.jdom.output.*;
import org.jdom.input.*;
import java.io.*; public class TestJDOM
{
public static void main(String args[])throws Exception
{ //SAXBuilder builds a JDOM tree using SAX.
SAXBuilder sb = new SAXBuilder(); //从文件构造一个Document,因为XML文件中已经指定了编码,所以这里不必了
Document doc = sb.build(new FileInputStream("exampleA.xml")); //加入一条处理指令
ProcessingInstruction pi = new ProcessingInstruction ("xml-stylesheet","href=\"greeting.css\" type=\"text/css\"");
doc.addContent(pi);
Element root = doc.getRootElement(); //得到根元素
java.util.List books = root.getChildren(); //得到根元素所有子元素的集合
Element book = (Element)books.get(0); //得到第一个book元素
//为第一本书添加一条属性
Attribute a = new Attribute("hot","true");
book.setAttribute(a);
Element author = book.getChild("author"); //得到指定的字元素
author.setText("王五"); //将作者改为王五
//或 Text t = new Text("王五");book.addContent(t);
Element price = book.getChild("price"); //得到指定的字元素
//修改价格,比较郁闷的是我们必须自己转换数据类型,而这正是JAXB的优势
price.setText(Float.toString(50.0f)); String indent = " ";
boolean newLines = true;
XMLOutputter outp = new XMLOutputter(indent,newLines,"gb2312");
outp.output(doc, new FileOutputStream("exampleB.xml")); }
}
==================
exampleA.xml
<?xml version="1.0" encoding="gb2312"?>
<bookList>
<book>
<name>Java编程入门</name>
<author>张三</author>
<publishDate>2002-6-6</publishDate>
<price>35.0</price>
</book>
<book>
<name>XML在Java中的应用</name>
<author>李四</author>
<publishDate>2002-9-16</publishDate>
<price>92.0</price>
</book>
</bookList> 所需要的包要下载
import org.jdom.output.*;
import org.jdom.input.*;
import java.io.*; public class TestJDOM
{
public static void main(String args[])throws Exception
{ //SAXBuilder builds a JDOM tree using SAX.
SAXBuilder sb = new SAXBuilder(); //从文件构造一个Document,因为XML文件中已经指定了编码,所以这里不必了
Document doc = sb.build(new FileInputStream("exampleA.xml")); //加入一条处理指令
ProcessingInstruction pi = new ProcessingInstruction ("xml-stylesheet","href=\"greeting.css\" type=\"text/css\"");
doc.addContent(pi);
Element root = doc.getRootElement(); //得到根元素
java.util.List books = root.getChildren(); //得到根元素所有子元素的集合
Element book = (Element)books.get(0); //得到第一个book元素
//为第一本书添加一条属性
Attribute a = new Attribute("hot","true");
book.setAttribute(a);
Element author = book.getChild("author"); //得到指定的字元素
author.setText("王五"); //将作者改为王五
//或 Text t = new Text("王五");book.addContent(t);
Element price = book.getChild("price"); //得到指定的字元素
//修改价格,比较郁闷的是我们必须自己转换数据类型,而这正是JAXB的优势
price.setText(Float.toString(50.0f)); String indent = " ";
boolean newLines = true;
XMLOutputter outp = new XMLOutputter(indent,newLines,"gb2312");
outp.output(doc, new FileOutputStream("exampleB.xml")); }
}
==================
exampleA.xml
<?xml version="1.0" encoding="gb2312"?>
<bookList>
<book>
<name>Java编程入门</name>
<author>张三</author>
<publishDate>2002-6-6</publishDate>
<price>35.0</price>
</book>
<book>
<name>XML在Java中的应用</name>
<author>李四</author>
<publishDate>2002-9-16</publishDate>
<price>92.0</price>
</book>
</bookList> 所需要的包要下载
Document doc = ...DocumentBuilderFactory->newDocumentBuilder->parse
www.xml.com
上去看看
<!--这个JSP文件,是将数据库中得数据导入保存到xml文档中-->
<html>
<head>
<title>SQL connect Test</title>
</head>
<%@ page import="java.sql.*" %>
<%@ page import="java.util.*" %>
<%@ page import="sql.UpsInforParser" %>
<!-- -->
<%
String cname;
String ename;
String producer;
String actor;
String pic;
String conn;
int line = 0;
BitSet bst = new BitSet(0);
UpsInforParser parser = new UpsInforParser();
String[] strArr = new String[50000]; Class.forName("com.jnetdirect.jsql.JSQLDriver");
conn = "jdbc:JSQLConnect://localhost/database=media/user=sa";
Connection Conn = DriverManager.getConnection(conn);
java.sql.Statement SQLStatement = Conn.createStatement();
String Query = "SELECT ID, NAME_CH,NAME_EN,PRODUCER,ACTOR,PIC FROM MEDIAINFOR";
ResultSet SQLResult = SQLStatement.executeQuery(Query);
%>
<table border = 1 cellspacing=0 cellpadding=0>
<tr>
<td width=20><a href="sqltestxml.jsp">ID</a></td>
<td width=80>NAME_CH</td>
<td width=80>NAME_EN</td>
<td width=80>PRODUCER</td>
<td width=80>ACTOR</td>
<td width=100>PIC URL</td>
</tr> <%
strArr[line] = "<?xml version=\"1.0\" encoding=\"GB2312\"?>";
line++;
strArr[line] = "<DOCUMENT>";
line++;
while(SQLResult.next()){
strArr[line++] = "<FILM>";
strArr[line++] = "<ID>"+SQLResult.getString(1)+"</ID>";
strArr[line++] = "<CNAME>"+SQLResult.getString(2)+"</CNAME>";
strArr[line++] = "<ENAME>"+SQLResult.getString(3)+"</ENAME>";
strArr[line++] = "<PRODUCER>"+SQLResult.getString(4)+"</PRODUCER>";
strArr[line++] = "<ACTOR>"+SQLResult.getString(5)+"</ACTOR>";
strArr[line++] = "<IMG>"+SQLResult.getString(6)+"</IMG>";
strArr[line++] = "</FILM>";
%>
<tr>
<td width=20><%=SQLResult.getString(1)%></td>
<td width=80><%=SQLResult.getString(2)%></td>
<td width=80><%=SQLResult.getString(3)%></td>
<td width=80><%=SQLResult.getString(4)%></td>
<td width=80><%=SQLResult.getString(5)%></td>
<td width=40><img src="<%=SQLResult.getString(6)%>"></td>
</tr>
<%}
strArr[line++] = "</DOCUMENT>";
bst.set(line-1);
out.print("the all acount are: "+line);
parser.createDoc("..\\webapps\\test\\sql\\sqltest.xml",strArr,line);
Conn.close();
%>
</table>绝对通过,我正在使用!
下面是我调用的一个类,我套用了一般的DOM处理XML文档的方法,制作了相应的改动。package sql;
import org.w3c.dom.*;
import org.apache.xerces.parsers.DOMParser;
import java.io.*;public class UpsInforParser
{
private String[] displayStrings = new String[5000];
private String[] value = new String[5000];
private int numberDisplayLines = 0;
private Node c;
private Document doc;
private String[] str;
private int k = 0;
private String index;
public UpsInforParser(String[] data)
{
this.str = data;
}
public UpsInforParser()
{
}
public static void main(String[] args)
{
String[] s = {"tNAME","tIP","ZONE","POSITION","CODE"};
UpsInforParser parser = new UpsInforParser(s);
// parser.createDoc("data/upsinfor.xml");
//for(int loopIndex = 0;loopIndex < numberDisplayLines;loopIndex++)
//{
//System.out.println(displayStrings[loopIndex]);
//}
}
public void displayDocument(String xml,int num)
{
try
{
DOMParser parser = new DOMParser();
parser.parse(xml);
doc = parser.getDocument();
display(doc,"",num);
}
catch(Exception e)
{
e.printStackTrace(System.err);
}
}
//add the data to the upsinfor.xml
public void createDoc(String s,String[] data,int line)
{
//displayDocument(s,1);
this.displayStrings = data;
this.numberDisplayLines = line;
try
{
FileWriter filewriter = new FileWriter(s);
for(int loopIndex=0;loopIndex <numberDisplayLines;loopIndex++)
{
filewriter.write(displayStrings[loopIndex].toCharArray());
filewriter.write('\n');
}
filewriter.close();
}
catch(Exception e)
{
e.printStackTrace(System.err);
}
//debug code
for(int loopIndex = 0;loopIndex < numberDisplayLines;loopIndex++)
{
System.out.println(displayStrings[loopIndex]);
}
}
/*
pubic void setData(String s)
{
displayStrings[numberDisplayLines++] = s;
}
*/
//edit the data of the upsinfor.xml
public void editDoc(String s,String index)
{
this.index = index;
displayDocument(s,2);
try
{
FileWriter filewriter = new FileWriter(s);
for(int loopIndex=0;loopIndex <numberDisplayLines;loopIndex++)
{
filewriter.write(displayStrings[loopIndex].toCharArray());
filewriter.write('\n');
}
filewriter.close();
}
catch(Exception e)
{
e.printStackTrace(System.err);
}
//debug code
for(int loopIndex = 0;loopIndex < numberDisplayLines;loopIndex++)
{
System.out.println(displayStrings[loopIndex]);
}
}
//add data method
public void addUps(Node node)
{
if(node.getNodeName().equals("DOCUMENT"))
{
String[] childName = {"NAME","IP","ZONE","POSITION","CODE","TIB"};
Element[] childNode = new Element[childName.length];
Text[] textNode = new Text[childName.length];
Element addNode = doc.createElement("UPS");
for(int i =0;i<childName.length;i++)
{
childNode[i] = doc.createElement(childName[i]);
textNode[i] = doc.createTextNode(str[i]);
}
for(int j =0;j<childName.length;j++)
{
childNode[j].appendChild(textNode[j]);
addNode.appendChild(childNode[j]);
}
node.appendChild(addNode);
}
}
//edit data method
public void editUps(Node node)
{
int count = 0;
if(node.getNodeName().equals("NAME"))
{
NodeList list = node.getChildNodes();
for(int i=0;i<list.getLength();i++)
{
if(list.item(i).getNodeValue().trim().equals(index))
{
//System.out.println(list.item(i).getParentNode().getParentNode().getNodeName().trim());
NodeList nodeList = list.item(i).getParentNode().getParentNode().getChildNodes();
for(int j=0;j<nodeList.getLength();j++)
{
//System.out.println(nodeList.item(j).getNodeName()+" ");
NodeList nd = nodeList.item(j).getChildNodes();
for(int k=0;k<nd.getLength();k++)
{
// System.out.println(nd.item(k).getNodeValue());
nd.item(k).setNodeValue(str[count]);
count++;
}
}
//System.out.println(node.getNodeName()+"'s value is "+list.item(i).getNodeValue());
}
}
}
}
//display the xml document's data
public void display(Node node,String indent,int flag)
{
if(node==null)
{return;}
int type = node.getNodeType();
switch(type)
{
//deal with the document node
case Node.DOCUMENT_NODE:
{
displayStrings[numberDisplayLines]=indent;
displayStrings[numberDisplayLines]+=
"<?xml version=\"1.0\" encoding=\""+
"GB2312"+"\"?>";
numberDisplayLines++;
display(((Document)node).getDocumentElement(),"",flag);
break;
}
//deal with the elements node
case Node.ELEMENT_NODE:
{
//add ups data
if(flag==1)
{addUps(node);}
//edit the ups data
if(flag==2)
{editUps(node);}
//display the data
displayStrings[numberDisplayLines] = indent;
displayStrings[numberDisplayLines]+="<";
displayStrings[numberDisplayLines]+=node.getNodeName();
//deal with the elements node's attribute
int length =(node.getAttributes()!=null)?
node.getAttributes().getLength():0;
Attr attributes[] = new Attr[length];
for(int loopIndex=0;loopIndex<length;loopIndex++)
{
attributes[loopIndex] =
(Attr)node.getAttributes().item(loopIndex);
}
for(int loopIndex=0;loopIndex<attributes.length;loopIndex++)
{
Attr attribute = attributes[loopIndex];
displayStrings[numberDisplayLines]+=" ";
displayStrings[numberDisplayLines]+= attribute.getNodeName();
displayStrings[numberDisplayLines]+="=\"";
displayStrings[numberDisplayLines]+= attribute.getNodeValue();
displayStrings[numberDisplayLines]+="\"";
}
displayStrings[numberDisplayLines]+=">";
//deal with the node's child node
numberDisplayLines++;
NodeList childNodes = node.getChildNodes();
if(childNodes!=null)
{
length = childNodes.getLength();
indent += " ";
for(int loopIndex=0;loopIndex<length;loopIndex++)
{
display(childNodes.item(loopIndex),indent,flag);
}
}
break;
}
/*
case Node.CDATA_SECTION_NODE:
{
displayStrings[numberDisplayLines] = indent;
displayStrings[numberDisplayLines] +="<![CDATA[";
displayStrings[numberDisplayLines] +=node.getNodeValue();
displayStrings[numberDisplayLines] +="]]>";
numberDisplayLines++;
break;
}
*/
case Node.TEXT_NODE:
{
displayStrings[numberDisplayLines] = indent;
String newText = node.getNodeValue().trim();
if(newText.indexOf("\n") < 0 && newText.length() > 0)
{
displayStrings[numberDisplayLines] += newText;
numberDisplayLines++;
}
break;
}
case Node.PROCESSING_INSTRUCTION_NODE:
{
displayStrings[numberDisplayLines] = indent;
displayStrings[numberDisplayLines] +="<?";
displayStrings[numberDisplayLines] += node.getNodeName();
String text = node.getNodeValue();
if(text != null && text.length()> 0)
{
displayStrings[numberDisplayLines] += text;
}
displayStrings[numberDisplayLines] +="?>";
numberDisplayLines++;
break;
}
}
if(type == Node.ELEMENT_NODE)
{
displayStrings[numberDisplayLines] = indent.substring(0,indent.length()-1);
displayStrings[numberDisplayLines] +="</";
displayStrings[numberDisplayLines] += node.getNodeName();
displayStrings[numberDisplayLines] += ">";
numberDisplayLines++;
indent += " ";
}
}
}