鸿 网 互 联 www.68idc.cn

当前位置 : 服务器租用 > 手机系统开发 > J2ME > >

dom4j解析XML文档 - Ajian

来源:互联网 作者:佚名 时间:2015-08-02 08:08
dom4j 的特点:必须一层一层获


dom4j的特点:必须一层一层获取。

package cn.itcast.sax;

 

import java.io.IOException;

import java.util.ArrayList;

import java.util.List;

 

import javax.xml.parsers.ParserConfigurationException;

import javax.xml.parsers.SAXParser;

import javax.xml.parsers.SAXParserFactory;

 

import org.xml.sax.Attributes;

import org.xml.sax.SAXException;

import org.xml.sax.XMLReader;

import org.xml.sax.helpers.DefaultHandler;

 

public class Demo3 {

       public static void main(String[] args) throws IOException, SAXException, ParserConfigurationException {

              //获得解析工厂

              SAXParserFactory factory = SAXParserFactory.newInstance();

              //得到解析器

              SAXParser sp = factory.newSAXParser();

              //得到读取器

              XMLReader reader = sp.getXMLReader();

              //设置内容处理器(implements Contenthandlerextends DefaultHandler)

              reader.setContentHandler(new BeanListHandler());

              //读取XML文档内容

              reader.parse("src/book.xml");

              //XML文档中的每一本书封装到一个book对象,并把多个book对象放在一个list集合返回

             

       }

}

class BeanListHandler extends DefaultHandler {

       private List list = new ArrayList();

       private String currentTag;

       private Book book;

 

       @Override

       public void startElement(String uri, String localName, String name,

                     Attributes attributes) throws SAXException {

              // TODO Auto-generated method stub

              currentTag = name;

              if ("".equals(currentTag)) {

                     book = new Book();

              }

 

       }

 

       @Override

       public void characters(char[] ch, int start, int length)

                     throws SAXException {

              if ("书名".equals(currentTag)) {

                     String name = new String(ch, start, length);

                     book.setName(name);

              }

              if ("作者".equals(currentTag)) {

                     String author = new String(ch, start, length);

                     book.setAuthor(author);

              }

              if ("售价".equals(currentTag)) {

                     String price = new String(ch, start, length);

                     book.setAuthor(price);

              }

       }

 

       @Override

       public void endElement(String uri, String localName, String qName)

                     throws SAXException {

              if ("".equals("name")) {

                     list.add(book);

                     book = null;

              }

              currentTag = null;

       }

       public List getList(){

              return list;

       }

}

 

publicclass Demo1 {

/*  @Test

    public void readAttr() throws DocumentException{

       SAXReader reader=new SAXReader();

       Document document=reader.read(new File("src/book.xml"));

       Element root=document.getRootElement();

       Element book=(Element)root.element("").get(1);

       String value=book.element("书名").attribute("name").getValue();

       System.out.println(value);

    }*/

    @Test

    publicvoid add()throws DocumentException, IOException{

       SAXReader reader=new SAXReader();

       Document document=reader.read(new File("src/book.xml"));

       Element book=document.getRootElement().element("");

       book.addElement("售价").setText("209");

      

       OutputFormat format=OutputFormat.createPrettyPrint();

       format.setEncoding("UTF-8");

      

       XMLWriter writer=new XMLWriter(new FileOutputStream("src/book.xml"),format);

       writer.write(document);

       writer.close();

             

    }

}

//在第一本书指定位置添加一个新的售价:<售价>209</售价>--更改保存了所有孩子的list集合的顺序

    @Test

    publicvoidadd2()throws DocumentException, IOException{

       SAXReader reader=new SAXReader();

       Document document=reader.read(new File("src/book.xml"));

       Element book=document.getRootElement().element("");

       List list=book.elements();

       Element price=DocumentHelper.createElement("售价");

       price.setText("309");

       list.add(2,price);

       OutputFormat format=OutputFormat.createPrettyPrint();

       format.setEncoding("UTF-8");

      

       XMLWriter writer=new XMLWriter(new FileOutputStream("src/book.xml"),format);

       writer.write(document);

       writer.close();

    }

    //删除指定节点

    @Test

    publicvoid delete()throws DocumentException, IOException{

       SAXReader reader=new SAXReader();

       Document document=reader.read(new File("src/book.xml"));

      

       Element price=document.getRootElement().element("").element("售价");

       price.getParent().remove(price);

      

       OutputFormat format=OutputFormat.createPrettyPrint();

       format.setEncoding("UTF-8");

       XMLWriter writer= new XMLWriter(new FileOutputStream("src/book.xml"),format);

       writer.write(document);

       writer.close();

    }

    //更新信息

    publicvoid update()throws Exception{

       SAXReader reader=new SAXReader();

       Document document=reader.read(new File("src/book.xml"));

      

       Element book=(Element) document.getRootElement().elements("").get(1);

       book.element("作者").setText("黎活明");

       OutputFormat format=OutputFormat.createPrettyPrint();

       format.setEncoding("UTF-8");

       XMLWriter writer= new XMLWriter(new FileOutputStream("src/book.xml"),format);

       writer.write(document);

       writer.close();

    }

XPath

XPath模拟登陆

publicclass Demo5 {

    publicstaticvoid main(String[] args)throws Exception{

          String username="aaa";

          String password="123";

          //检测XML文档是否有匹配的用户名和密码

          SAXReader reader=new SAXReader();

          Document document=reader.read(new File("src/users.xml"));

          Node node=document.selectSingleNode("//user[@username='"+username+"' and @password='"+password+"']");

          if(node==null){

             System.out.println("您输入的用户名或密码有误");

          }

          else{

             System.out.println("登陆成功");

          }

    }

}

XML Schema

XML Schema文件自身就是一个XML文件,扩展名为.xsd

一个XML Schema文档通常称之为模式文档(约束文档),遵循这个文档书写的XML文件称之为实例文档!

XML Schema中,每个约束模式文档都可以被赋以一个唯一的名称空间,名称空间用一个唯一的URIUniform Resource Identifier,统一资源标识符)表示。

Schema 语法:

定义简单元素:<xs:element name=”XXXX” type=”yyy”/>

           XXX:元素的名称,yyy:元素的数据类型

最常用的类型:

xs:string /xs:decimal/xs:integer/xs:boolean/xs:date/xs:time

一道打印M的面试题(平面图形题--通用解题方案:利用二维数组)

publicclass MTest {

    publicstaticvoid main(String[] args){

       int x=2;

       int y=0;

       boolean flag=true;

       int arr[][]=newint[3][9];

       for(int i=1;i<=9;i++){

          arr[x][y]=i;

          y++;

          if(flag==false){

             x--;

             

          }

          if(flag==true){

             x++;

          }

          if(x<0){

             flag=true;

             x+=2;

          }

          if(x>2){

             flag=false;

             x-=2;

          }

       }

       for(int i=0;i<arr.length;i++){

          for(int j=0;j<arr[i].length;j++){

             if(arr[i][j]==0){

                 System.out.print(" ");

             }else{

                 System.out.print(arr[i][j]);

             }

          }

          System.out.println();

       }

             

    }

}

 

 

 

网友评论
<