分享

DOM4J对XML文档的读写增删改等

 欢欢2008 2010-11-02
DOM4J对XML文档的读写增删改等
用DOM4J对XML文档的读写增删改等操作,是我自己的练习题,没有整理和注释,只做以后查看之用。主要方法在构造函数中做了简单说明,涉及到的XML、XSD、DTD文档不再写入。
package xml.dom4j.wkjava;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Iterator;
import java.util.List;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

public class Test {

Document doc = null;

  public Test() throws DocumentException, IOException, SAXException {
      Document doc = loadXML("class.xml"); //载入XML文档
     System.out.println(doc.asXML());

      printDoc(doc);
//打印XML文档

     storeDoc(doc,
"new.xml"); //把XML文档存入硬盘

     doc = valideDoc(
"class.xml");  //校验dtd XML文档
     printDoc(doc);

     doc = validateDocBySxd(
"classSchema.xml"); //校验Schema文档
     printDoc(doc);

     String url = getClass().getResource(
"/xml/dom4j/wkjava/class.xsd").toString();
     doc = validateDocBySxd(
"classSchema.xml",url); //校验Schema文档(俩参数)
     printDoc(doc);

     doc = createDoc();
//创建Schema文档
    storeDoc(doc,
"root.xml");

     doc = validateDocBySxd(
"classSchema.xml");
     updateZip(doc,
"102202"); //在文档中修改原属
    printDoc(doc);

     doc = validateDocBySxd(
"classSchema.xml");
     printNames(doc);  
//打印文档中所有学生名字
    System.out.println(getStudentCount(doc));
  }
public static void main(String[] args) {
try {
new Test();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (DocumentException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
}
}

public Document loadXML(String xmlfile)
    throws FileNotFoundException, DocumentException{
    SAXReader reader = new SAXReader();
    doc = reader.read(new FileInputStream(xmlfile));
    return doc;
}

    public void printDoc(Document doc) throws IOException {
     Writer out = new OutputStreamWriter(System.out,
"gb2312");
    OutputFormat format = OutputFormat.createPrettyPrint();
    XMLWriter writer = new XMLWriter(out, format);
    writer.write(this.doc);
    out.flush();
}
    
    public void storeDoc(Document doc,String filename) throws IOException {
     Writer out = new OutputStreamWriter(new FileOutputStream(filename),
"utf-8");
    OutputFormat format = OutputFormat.createPrettyPrint();
    XMLWriter writer = new XMLWriter(out, format);
    writer.write(this.doc);
    printDoc(doc);
    out.close();
}

    public Document valideDoc(String xmlfile) throws DocumentException, IOException{
     EntityResolver resolver = new EntityResolver(){
public InputSource resolveEntity(String publicId, String systemId)
    throws SAXException, IOException {
if(publicId.equals(
"//class from weiking")){
InputStream in = new FileInputStream(
"class.dtd");
return new InputSource(in);
}
return null;
}  
     };
     SAXReader reader = new SAXReader(true);
     reader.setEntityResolver(resolver);
     Document doc = reader.read(new FileInputStream(xmlfile));
     return doc;
    }
    
    public Document validateDocBySxd(String xmlfile) throws SAXException, DocumentException, IOException{
     SAXReader reader = new SAXReader(true);
     reader.setFeature(
"http:///xml/features/validation/schema",true);
     Document doc = reader.read(new FileInputStream(xmlfile));
     return doc;
    }
    
    public Document validateDocBySxd(String xmlfile,String SchemaUrl)
        throws SAXException, FileNotFoundException, DocumentException{
     SAXReader reader = new SAXReader(true);
     reader.setFeature(
"http:///sax/features/validation", true);
reader.setFeature(
"http:///xml/features/validation/schema",true);
reader.setFeature(
"http:///xml/features/validation/schema-full-checking",true);
reader.setProperty(
"http:///xml/properties/schema/external-noNamespaceSchemaLocation",SchemaUrl);
     Document doc = reader.read(new FileInputStream(xmlfile));
     return doc;
    }
    
    public Document createDoc() {
        Document doc = DocumentHelper.createDocument();
        Element root = doc.addElement(
"root" );

        Element author2 = root.addElement(
"author" )
          .addAttribute(
"name", "Toby" )
          .addAttribute(
"location", "Germany" )
          .addText(
"Tobias Rademacher" );

        Element author1 = root.addElement(
"author" )
          .addAttribute(
"name", "James" )
          .addAttribute(
"location", "UK" )
          .addText(
"James Strachan" );

        return doc;
      }

    public void updateZip(Document doc,String zip){
     String xpath =
"/Class/Teacher/zip";
     Element e = (Element)doc.selectSingleNode(xpath);
     e.setText(zip);
    }
    
    public void printNames(Document doc){
     String xpath =
"/Class/Students/Student/name";
     List list = doc.selectNodes(xpath);
     for(Iterator i = list.iterator(); i.hasNext();){
     Element e = (Element)i.next();
     System.out.println(e.element(
"last").getText() + e.valueOf("first"));
     }
    }
    
    public int getStudentCount(Document doc){
     int count = 0;
     String xpath =
"count(/Class/Students/Student)";
     count = doc.numberValueOf(xpath).intValue();
//     String value = doc.valueOf(xpath);
//     count = Integer.parseInt(value);
     return count;
  
weiking   2006-04-20 09:32:07 评论:2   阅读:6407   引用:0
没注释 @2008-11-18 16:15:59  司马卧龙
没注释别人看着困难 你自己看着就不累么 哈哈
我写的通用,大家可以交流 @2007-02-17 17:08:13  jomper
http://blog.csdn.net/Jomper/archive/2006/03/23/636548.aspx
http://code.google.com/p/jomperxo/

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多