首页 > 编程 > Java > 正文

JAVA 遇上XML|通过DOM来解析XML文件

2019-11-09 20:57:40
字体:
来源:转载
供稿:网友

解析xml分为 DOM、SAX、DOM4J、JDOM四种方式,先从DOM入手。

package DOM;import java.io.IOException;import java.rmi.server.SocketSecurityException;import javax.xml.parsers.DocumentBuilder;import javax.xml.parsers.DocumentBuilderFactory;import javax.xml.parsers.ParserConfigurationException;import org.w3c.dom.Document;import org.w3c.dom.NamedNodeMap;import org.w3c.dom.Node;import org.w3c.dom.NodeList;import org.xml.sax.SAXException;public class xml_dom { public static void main(String arg[]){// 通过DocumentbuilderFactory.newInstance()方法构建一个DocumentbuilderFactory对象 dbf DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); try {// 通过DocumentBuilderFactory去创建DocumentBuilder对象db DocumentBuilder db = dbf.newDocumentBuilder();// 通过DocumentBuilder.parse()方法,传入xml文件路径作为参数,将StudentList.xml加载到项目中,构建出Document对象document// 注意Document是在org.w3c.dom.Document下的 Document document = db.parse("StudentList.xml");// 获取student的所有节点 存储在NodeList里 NodeList studentList =document.getElementsByTagName("student");// 通过循环依次取出所有节点 for(int i = 0;i < studentList.getLength();i++){// 通过Node存储取出的节点 Node node = studentList.item(i);// 获取该节点的所有属性(只尖括号内的属性),存储于NamedNodeMap中 NamedNodeMap attrs = node.getAttributes();// 通过循环依次取出每个属性 for(int j = 0;j < attrs.getLength();j++){ Node attr = attrs.item(j);// 输出该节点的属性名 System.out.PRint("属性名:"+attr.getNodeName());// 输出该节点的属性的值 System.out.println("--属性值:"+attr.getNodeValue()); }// 输出子节点的话通过Node.getchildNodes获取所有子节点 存到NodeList中 NodeList childrenNode = node.getChildNodes();// 节点分为三种类型 ELEMENT_NODE、ATTRIBUTE_NODE、TEXT_NODE // 其中一对尖括号是Element,文本内容是Text,尖括号内的属性为Attrubute// 观察xml文件不难得出每个student节点下拥有7个子节点 System.out.println(childrenNode.getLength()); for(int j = 0;j < childrenNode.getLength();j++){ Node child = childrenNode.item(j);// 这里输出Element节点的属性名和值 if(child.getNodeType()==Node.ELEMENT_NODE){ System.out.print("节点名:"+child.getNodeName());// 因为Element的NodeValue返回值固定为null,通过getFirstChild获取该节点的下的第一个孩子节点,本次操作中即为TEXT_NODE类型// TEXT_NODE的返回值为文本内容 System.out.println("--节点值:"+child.getFirstChild().getNodeValue());// 也可以通过getTextContent获取节点下的所有TEXT类型的返回值// System.out.println("--节点值:"+child.getTextContent()); }else{ System.out.println("节点名:"+child.getNodeName()); System.out.println("节点值:"+child.getNodeValue()); } } System.out.println("============="); } } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }}

整理了XML节点的分类 这里写图片描述


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表