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

来源:互联网 发布:java三大框架ssm面试题 编辑:程序博客网 时间:2024/05/18 01:09
用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://apache.org/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://xml.org/sax/features/validation", true);
reader.setFeature(
"http://apache.org/xml/features/validation/schema",true);
reader.setFeature(
"http://apache.org/xml/features/validation/schema-full-checking",true);
reader.setProperty(
"http://apache.org/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;
  
 
原创粉丝点击