标签:.class set too 内容 address nts package string bar
xml文件
<?xml version="1.0" encoding="UTF-8"?> <Object> <student> <stuName>张三</stuName> <stuAddress>郑州</stuAddress> <stuTel>111</stuTel> </student> <user> <userName>aaa</userName> <userAge>100</userAge> <userSex>男</userSex> </user> <book> <bookName>语文</bookName> <bookAuthor>XXX</bookAuthor> <bookPrice>100</bookPrice> </book> </Object>
操作方法
package com.xml; import java.io.File; import java.net.URL; import java.util.List; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.io.SAXReader; import com.bean.Book; import com.bean.Student; import com.bean.User; public class SaxXml { public static void main(String[] args) throws Exception { //File file=new File("config/student.xml"); //获取dom树 URL url=SaxDbXml.class.getClassLoader().getResource("student.xml"); SAXReader sax=new SAXReader(); //Document dom=sax.read(file); Document dom = sax.read(url); //获取dom树里面的根节点 Element rootEle=dom.getRootElement(); //获取根节点下的节点元素 List<Element> eleList=rootEle.elements(); //System.out.println(eleList.size());a //循环获取每个节点元素 for(int i=0;i<eleList.size();i++){ Element childEle=eleList.get(i); String name=childEle.getName(); if(name.equalsIgnoreCase("student")){ Student stu=new Student(); //获取节点下面的子节点 List<Element> childList=childEle.elements(); for(int j=0;j<childList.size();j++){ Element ele=childList.get(j); String eleName=ele.getName(); if(eleName.equalsIgnoreCase("stuName")){ stu.setStuName(ele.getText()); //System.out.println(ele.getText()); }else if(eleName.equalsIgnoreCase("stuAddress")){ stu.setStuAddress(ele.getText()); }else if(eleName.equalsIgnoreCase("stuTel")){ stu.setStuTel(ele.getText()); } } }else if(name.equalsIgnoreCase("user")){ User user=new User(); //获取子节点元素 List<Element> userList=childEle.elements(); for(int k=0;k<userList.size();k++){ Element userEle=userList.get(k); //判断子节点元素的名称,进行相应的存值 if(userEle.getName().equalsIgnoreCase("userName")){ user.setUserName(userEle.getText()); }else if(userEle.getName().equalsIgnoreCase("userSex")){ user.setUserSex(userEle.getText()); }else if(userEle.getName().equalsIgnoreCase("userAge")){ user.setUserAge(userEle.getText()); } } }else if(name.equalsIgnoreCase("book")){ Book book=new Book(); List<Element> bookList=childEle.elements(); for(int k=0;k<bookList.size();k++){ Element bookEle=bookList.get(k); String eleName=bookEle.getName(); if(eleName.equalsIgnoreCase("bookName")){ book.setBookName(bookEle.getText()); }else if(eleName.equalsIgnoreCase("bookAuthor")){ book.setBookAuthor(bookEle.getText()); }else if(eleName.equalsIgnoreCase("bookPrice")){ book.setBookPrice(bookEle.getText()); } } } } } }
标签:.class set too 内容 address nts package string bar
原文地址:https://www.cnblogs.com/Life-is-Demo/p/9113764.html