关闭

dom解释xml

199人阅读 评论(0) 收藏 举报

一、创建xml

<?xml version="1.0" encoding="UTF-8"?>
<persons>
 <person id="23">
  <name>liming</name>
  <age>30</age>
 </person>
 <person id="20">
  <name>lixiangmei</name>
  <age>25</age>
 </person>
</persons>

二、创建domain


public class Person {
 private Integer id;
 private String name;
 private Short age;
 
 public Person(){}
 
 public Person(Integer id, String name, Short age) {
  this.id = id;
  this.name = name;
  this.age = age;
 }
 
 public Integer getId() {
  return id;
 }
 public void setId(Integer id) {
  this.id = id;
 }
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public Short getAge() {
  return age;
 }
 public void setAge(Short age) {
  this.age = age;
 }
 @Override
 public String toString() {
  return "Person [age=" + age + ", id=" + id + ", name=" + name + "]";
 }
 
}

三、创建解释类

public class DOMPersonService {

 public static List<Person> getPersons(InputStream inStream) throws Throwable{
  List<Person> persons = new ArrayList<Person>();
  DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
  DocumentBuilder builder = factory.newDocumentBuilder();
  Document documnet = builder.parse(inStream);
  Element root = documnet.getDocumentElement();
  NodeList personNodes = root.getElementsByTagName("person");//根据节点名称取得node list
  for(int i=0 ; i < personNodes.getLength(); i++){
   Person person = new Person();
   Element personElement = (Element)personNodes.item(i);//Element是从Node继承来的
   person.setId(new Integer(personElement.getAttribute("id")));//取得属性
   NodeList personChilds = personElement.getChildNodes();
   for(int y=0 ; y < personChilds.getLength(); y++){
    if(personChilds.item(y).getNodeType()==Node.ELEMENT_NODE){//判断节点类型
     Element childElement = (Element)personChilds.item(y);
     if("name".equals(childElement.getNodeName())){//取得Node的名字
      person.setName(childElement.getFirstChild().getNodeValue());//取得文本节点的值
     }else if("age".equals(childElement.getNodeName())){
      person.setAge(new Short(childElement.getFirstChild().getNodeValue()));
     }
    }
   }
   persons.add(person);
  }
  return persons;
 }
}

 

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:240410次
    • 积分:2318
    • 等级:
    • 排名:第16123名
    • 原创:28篇
    • 转载:51篇
    • 译文:0篇
    • 评论:36条
    文章分类
    最新评论