Dom4j --- 解析 XML 列子

原文:http://laravel.iteye.com/blog/246530


用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; 



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值