xml文件的编写/解析和元素定义

来源:互联网 发布:淘宝黑搜20单五天必爆 编辑:程序博客网 时间:2024/05/17 15:40

    最近接手一个项目的三期改造,代码是外包公司编写,交由我方先做第三期改造,看到项目中有用到自定义的" .dtd "文件,以前没见过,做了一下总结

1.项目中一个".dtd"文件demo  文件名cache-dict.dtd

<?xml version="1.0" encoding="UTF-8"?><!ELEMENT dicts (dict*)><!ELEMENT dict (from,key,val)><!ATTLIST dict id ID #REQUIRED               orgright (none|id|no) "none"><!ELEMENT from (#PCDATA)><!ATTLIST from name (exeid) "exeid"><!ELEMENT key (#PCDATA)><!ELEMENT val (#PCDATA)><!ATTLIST val separator CDATA "-">
 <!-- 一个xml文档demo--><?xml version="1.0" encoding="UTF-8"?><!DOCTYPE dicts SYSTEM "../../dtd/cache-dict.dtd"><!--引入dtd文件--><dicts>   <dict id="a">      <from name="exeid">zhao</from>      <key>value</key>      <val>text</val>   </dict>      <dict id="b">      <from name="exeid">qian</from>      <key>value</key>      <val>text</val>   </dict>      <dict id="c">      <from name="exeid">sun</from>      <key>value</key>      <val>text</val>   </dict>      <dict id="d">      <from name="exeid">li</from>      <key>value</key>      <val>text</val>   </dict></dicts>

?=0次或者1次,+=一次或者多次,*=0次或者多次


2.读取xml文档

import org.dom4j.Document;import org.dom4j.DocumentException;import org.dom4j.Element;import org.dom4j.io.SAXReader;
// 读取xml文件的方法
SAXReader saxReader = new SAXReader();Document doc = saxReader.read(f);// f为 File file = new file(“xml文档路径”)Element root = doc.getRootElement();// 获取 .dtd 文档中定义的<!element>属性的元素
if(root != null) {    Iterator itDicts = root.elementIterator();    if(itDicts != null) {
        while(itDicts.hasNext()) {           Element elDict = (Element)itDicts.next();           String sID = elDict.attributeValue("id");// 获取元素(节点)中的属性
           if(sID != null && !sID.equals("")) {                String orgright = elDict.attributeValue("orgright");                Element el = elDict.element("from");// 再获取节点中的from节点
                if(el != null) {                    String from = el.attributeValue("name");// 获取name属性为.dtd定义的<!attlist>                    if(from != null && !"".equals(from)) {                        String idVal = el.getTextTrim();// 获取节点中指定的值 例:zhao<from name="exeid">zhao</from>                    }                }           }      }    }}
3. DTD中的定义规则


必须列出所有节点,一个都不能少


1)元素
"*"星号  表示可以出现0-n次
"+"加号  表示可以出现1-n次
"|"   表示或(只能出现一个)
   如(phone|mobile)表示固话或手机二选一
"?"问号:  表示出现0或1此
#PCDATA 表示字符串


2)属性:
定义在开始标记中的键值对
dtd 规则_属性
1) <!ATTLIST 标记名称 属性名称 属性类型>
2) isbn CDATA #REQUIRED: 表示isbn属性是必须的
3) isbn CDATA #IMPLIED: 表示isbn属性不是必须的
4) hot CDATA"false" :表示hot默认值是false