使用dom解析xml

<?xml version="1.0" encoding="UTF-8" ?>
<students>
	<student>
		<name>qyy</name>
		<age>26</age>
		<sex>男</sex>
		<address>四川成都</address>
	</student>
	<student>
		<name>tt</name>
		<age>24</age>
		<sex>女</sex>
		<address>四川达州</address>
	</student>
</students> 
xml文件如上

下面使用dom操作来实现解析
 
	public Document getDocument(String fileName) {
		Document document = null;
		try {
			DocumentBuilderFactory factory = DocumentBuilderFactory
					.newInstance();
			DocumentBuilder builder = factory.newDocumentBuilder();
			document = builder.parse(new File(fileName));

		} catch (Exception e) {
			e.printStackTrace();
		}

		return document;
	}  public void paseXml(String fileName) {
		Document document = getDocument(fileName);
		NodeList nodeList = document.getElementsByTagName("student");
		for (int i = 0; i < nodeList.getLength(); i++) {
			StringBuilder sb = new StringBuilder();
			sb.append("姓名:"
					+ document.getElementsByTagName("name").item(i)
							.getFirstChild().getNodeValue());
			sb.append(" , ");
			sb.append("年龄:"
					+ document.getElementsByTagName("age").item(i)
							.getFirstChild().getNodeValue());
			sb.append(" , ");
			sb.append("性别:"
					+ document.getElementsByTagName("sex").item(i)
							.getFirstChild().getNodeValue());
			sb.append(" , ");
			sb.append("地址:"
					+ document.getElementsByTagName("address").item(i)
							.getFirstChild().getNodeValue());

			System.out.println(sb.toString());
		}
	} 

静态主方法:
	public static void main(String[] str) {
		TextXMl textXMl = new TextXMl();
		textXMl.paseXml("E:/java/example/src/com/example/test/student.xml");
	} 

生成的结果如下
姓名:qyy , 年龄:26 , 性别:男 , 地址:四川成都
姓名:tt , 年龄:24 , 性别:女 , 地址:四川达州
 

 

你可能感兴趣的:(xml,解析,dom)