public static List<Student>readXml() {
List<Student>list = new ArrayList<Student>()
//定义一个<a href="https://www.baidu.com/s?wd=dom%E8%A7%A3%E6%9E%90&tn=44039180_cpr&fenlei=mv6quAkxTZn0IZRqIHckPjm4nH00T1Y3uhnvryDYrjIBPyDYn1Rv0ZwV5Hcvrjm3rH6sPfKWUMw85HfYnjn4nH6sgvPsT6K1TL0qnfK1TL0z5HD0IgF_5y9YIZ0lQzqlpA-bmyt8mh7GuZR8mvqVQL7dugPYpyq8Q1RznjcYn1TLnH04rjcYnjTvPf" target="_blank" class="baidu-highlight">dom解析</a>器亮纳工厂实例
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance()
try {
//由工厂实例得到一个<a href="https://www.baidu.com/s?wd=dom%E8%A7%A3%E6%9E%90&tn=44039180_cpr&fenlei=mv6quAkxTZn0IZRqIHckPjm4nH00T1Y3uhnvryDYrjIBPyDYn1Rv0ZwV5Hcvrjm3rH6sPfKWUMw85HfYnjn4nH6sgvPsT6K1TL0qnfK1TL0z5HD0IgF_5y9YIZ0lQzqlpA-bmyt8mh7GuZR8mvqVQL7dugPYpyq8Q1RznjcYn1TLnH04rjcYnjTvPf" target="_blank" class="baidu-highlight">dom解析</a>器
DocumentBuilder dom = factory.newDocumentBuilder()
//找到<a href="https://www.baidu.com/s?wd=xml%E6%96%87%E6%A1%A3&tn=44039180_cpr&fenlei=mv6quAkxTZn0IZRqIHckPjm4nH00T1Y3uhnvryDYrjIBPyDYn1Rv0ZwV5Hcvrjm3rH6sPfKWUMw85HfYnjn4nH6sgvPsT6K1TL0qnfK1TL0z5HD0IgF_5y9YIZ0lQzqlpA-bmyt8mh7GuZR8mvqVQL7dugPYpyq8Q1RznjcYn1TLnH04rjcYnjTvPf" target="_blank" class="baidu-highlight">xml文档</a>
File file=new File("src/com/jereh/ch05/Students.xml")
Document doc=dom.parse(file)
//
Element root = doc.getDocumentElement()
NodeList stuNodeList = root.getChildNodes()
for (int i = 0i <stuNodeList.getLength()i++) {
Node stu = stuNodeList.item(i)
Student student = new Student()
if (stu != null &&stu.getNodeType() == Node.ELEMENT_NODE) {
/源雀/ System.out.println(stu)
Element stuElement = (Element) stu
student.setNo(stuElement.getAttribute("id"))
// stu.getAttributes().getNamedItem(null)
// Element stu=(Element)stuNodeList
NodeList info = stuElement.getChildNodes()
for (int j = 0j <info.getLength()j++) {
info.item(j).getNodeName()
Node n = info.item(j)
if ("name".equals(n.getNodeName())) {
// n.getFirstChild().getNodeValue()
student.setName(n.getLastChild().getNodeValue())
} else if ("age".equals(n.getNodeName())) {
student.setAge(Integer.parseInt(n.getFirstChild()
.getNodeValue()))
}
list.add(student)
}
}
}
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace()
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace()
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace()
}
// System.out.println(root.getNodeValue())
return list
}
如何运行吧。解析搜培念的世困过程,是“不可中桥知”的,除非你看研究JAVA的源码。先编辑好源码
再编译
javac MyClass.java
java MyClass 就可以运行
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)