转贴:
Java与XML(二)用java编写xml的读写程序 这是读取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."); 


}

解决方案 »

  1.   

    http://www.host01.com/Get/jsp/00040006/0542422193954316.htm
      

  2.   

    采用jdom方式import java.io.FileInputStream;
    import java.util.*;import org.jdom.Document;
    import org.jdom.Element;
    import org.jdom.input.SAXBuilder;
    public class ParseXml {
        public ParseXml() {
        }
     public static String getXmlData(String xmlFilePath,String mainTag,String subTag) {
            SAXBuilder builder = new SAXBuilder();
            String str="";
            try {
              Document doc = builder.build(new FileInputStream(xmlFilePath));
              Element root = doc.getRootElement();
              List child=null;
              if(subTag.equals("")){
                  child = root.getChildren(mainTag);
              }
             else if(!subTag.equals("")){
                 child = ((Element) root.getChildren(mainTag).get(0)).
                            getChildren(subTag);
             }
             Iterator it=child.iterator();
             while (it.hasNext()) {
                  Element c = (Element) it.next();
                  str+=c.getTextTrim()+"#";
              }
              if(str.endsWith("#"))str=str.substring(0,str.length()-1);
            } catch (Exception e) {
                System.out.println(e.getMessage());
                CatalogApp.sysLog.log(e.getMessage());
                return "";
            }
            if(str!=null) return str;
            return "";
        }
    }
      

  3.   

    搂主可以在网上查一查,有很多这方面的信息,有java自带的读写xml的
    也有别的开源的jar包,如:jdom等
      

  4.   

    搂住可以用JDOM+XPATH非常方便
      

  5.   

    楼主上google搜索“xmlwriter”有个例子程序很详细。
      

  6.   

    jakarta.apache.org 上的commons组件 看turial 有样列