Java知识积累——Sax解析xml文档

整体思路:Sax解析是将xml文档按Stream读入,一点一点的解析,香港服务器租用,不像Dom解析那样把文档全部加载到内存中,因此更适合实际情况的使用。Sax解析需要继承DefaultHandler,网站空间,重写其4个方法(startDocument、startElement、endElement、characters),分别用于处理xml的ElementNode(<>或</>)和TextNode(字符)。下面看一个例子:此程序将原本的xml文件中各个元素标签解析成对应的TagBean实例,每对标签会被解析成一个实例,并且按树状存储标签之间的关系。因为我的目的是要解析Spring IoC的配置信息,免备案空间,所以4个方法的处理都是基于Spring IoC配置规则而实现的,当你们解析特定的xml文档时,只要修改这4个方法的解析规则即可。

TagBean的代码:

TagBean { 2private String name; 3private Map<String,String> attrList = null; 4private ArrayList<TagBean> childList = new ArrayList<TagBean>();print(int count){ 7for(int i = 0; i < count; i++){ 8System.out.print(” “); 9 }10System.out.print(name+”:”);11if(attrList != null){12Iterator<String> keySetItr = attrList.keySet().iterator();13while(keySetItr.hasNext()){14String key = keySetItr.next();15System.out.print(key +”–“+attrList.get(key)+”\t”);16 }17 System.out.println();18}else{19 System.out.println();20 }21if(childList.size() > 0){22int newCount = ++count;23for(TagBean temp : childList){24 temp.print(newCount);25 }26}else{27return;28 }29 } String getName() {32return name;33 } setName(String name) {35this.name = name;36 }37public Map<String, String> getAttrList() {38if(attrList == null){39attrList = new HashMap<String,String>();40 }41return attrList;42 }setAttrList(Map<String, String> attrList) {44this.attrList = attrList;45 }46public ArrayList<TagBean> getChildList() {47return childList;48 } setChildList(TagBean childTag){50this.childList.add(childTag);51 }5253 }那段雨骤风狂。人生之旅本就是风雨兼程,是要说曾经拥有,

Java知识积累——Sax解析xml文档

相关文章:

你感兴趣的文章:

标签云: