import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import com.android.mldn.domain.Person;
public class DOMPersonService {
/**
* 采用DOM解析XML内容
*/
public static List
throws Throwable{
List
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
//对xml 文件进行解析
Document document = builder.parse(inStream);
//得到元素的根节点
Element root = document.getDocumentElement();
//得到person 节点
NodeList personNodes = root.getElementsByTagName("person");
//遍历内部节点元素
for (int i = 0; i < personNodes.getLength(); i++) {
//创建一个person 实例
Person person = new Person();
Element personElement = (Element) personNodes.item(i);
//查找 名称为 id 的元素节点
person.setId(new Integer(personElement.getAttribute("id")));
//读取 子节点
NodeList personChilds = personElement.getChildNodes();
for (int j = 0; j < personChilds.getLength(); j++) {
//判断当前节点是否是元素类型节点
if (personChilds.item(j).getNodeType() == Node.ELEMENT_NODE) {
Element childElement = (Element)personChilds.item(j);
if ("name".equals(childElement.getNodeName())) {
person.setName(childElement.getFirstChild().getNodeValue());
}else if ("age".equals(childElement.getNodeName())) {
person.setAge(new Short(childElement.getFirstChild().getNodeValue()));
}
}
}
persons.add(person);
}
return persons;
}
}