您的位置:首页 > 编程语言 > Java开发

使用Java解析XML文件并在控制台原样输出

2017-09-01 00:00 465 查看
这是我第一次写博客,今天初次接触XML文件的解析,感觉有点绕,但是最后还是自己做出来了,想想还是写写吧,记录自己的成长历程

xml文件样式:

<?xml version="1.0" encoding="utf-8"?>
<students>
<student id="001">
<name>张三</name>
<age>23</age>
<address>USA</address>
</student>
<student id="002">
<name>李四</name>
<age>24</age>
<address>USA</address>
</student>
<student id="003">
<name>王五</name>
<age>25</age>
<address>USA</address>
</student>
</students>

Java代码:

package com.gem.java.parsexml;

import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class CompleteParseXML {
public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException {
DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
DocumentBuilder builder=factory.newDocumentBuilder();
Document document=builder.parse("src/hello.xml");

Element students=document.getDocumentElement();
System.out.print("<"+students.getNodeName()+">");
NodeList stuNodeList=students.getChildNodes();
for (int i = 0; i < stuNodeList.getLength(); i++) {
Node stuNode=stuNodeList.item(i);
printNode(stuNode);
}
System.out.print("</"+students.getNodeName()+">");
}

static void printNode(Node node){
if(node.getNodeType()==Node.ELEMENT_NODE){
System.out.print("<"+node.getNodeName());
NamedNodeMap attr=node.getAttributes();
for (int i = 0; i < attr.getLength(); i++) {
Node attrNode=attr.item(i);
System.out.print(" "+attrNode.getNodeName()+"=\""+attrNode.getNodeValue()+"\"");
}
System.out.print(">");
NodeList childsNode=node.getChildNodes();
for (int i = 0; i < childsNode.getLength(); i++) {
Node childNode=childsNode.item(i);
printNode(childNode);
}
System.out.print("</"+node.getNodeName()+">");
}else {
System.out.print(node.getNodeValue());
}

}
}
首先要获取到文档的根节点元素,节点有元素节点,属性节点,文本节点。标签 <student id="001"></student>下有七个子节点,这个很容易被弄错,红色标出的是4个文本节点,另外3个标签是元素节点。我个人感觉DOM操作的API有点不按套路出牌,比如获取节点NodeList类型变量中获取子节点用item(index),我直接用了get(index),发现不对,又用了数组的取值方式,也是不对,最后才弄出来,还有获取其长度时使用getLength(),而不是length或者size(),这些都是要注意的,很容易因为惯性就写错了。我代码写的不是很好,如果有什么问题和建议欢迎大家给我提,就写到这吧。加油!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: