1.目录结构
2019-03-12 20-37-51屏幕截图.png2.java代码
//获取配置文件
URL url = new XmlTest().getClass().getClassLoader().getResource("testXml.xml");
try {
//获取documentBuilder对象
DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
try {
//获取dicument对象 parse方法有多个重载方法
Document document = documentBuilder.parse(Files.newInputStream(Paths.get(url.toURI())));
//获取element
Element documentElement = document.getDocumentElement();
System.out.println("documentElement.getTagName()="+documentElement.getTagName());
//documentElement.getTagName()=people
//获取当前节点下面的所有节点
NodeList nodeList = documentElement.getChildNodes();
//遍历节点
for(int i=0;i<nodeList.getLength();i++){
//预期是三个 top body bottom
/* 实际输出七个
nodeList.item(i) = #text
nodeList.item(i) = top
nodeList.item(i) = #text
nodeList.item(i) = body
nodeList.item(i) = #text
nodeList.item(i) = bottom
nodeList.item(i) = #text
*/
System.out.println("nodeList.item(i) = " + nodeList.item(i).getNodeName());
}
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (URISyntaxException e) {
e.printStackTrace();
}
} catch (ParserConfigurationException e) {
e.printStackTrace();
}
3.xml文件
<?xml version="1.0" encoding="utf-8" ?>
<people>
<top>
<eye glasses="200">左眼</eye>
<nose>鼻子</nose>
<eye glasses="210">右眼</eye>
<mouth>嘴巴</mouth>
</top>
<body>
<arm>左手</arm>
<chest>胸口</chest>
<arm>右手</arm>
</body>
<bottom>
<foot>左脚</foot>
<foot>右脚</foot>
</bottom>
</people>
加强1.1
//获取当前节点下面的所有节点
NodeList nodeList = documentElement.getChildNodes();
//遍历节点
for(int i=0;i<nodeList.getLength();i++){
Node item = nodeList.item(i);
//这样就可以省略掉空格了
if(item instanceof Element) {
System.out.println("nodeList.item(i) = " + item.getNodeName());
/*
nodeList.item(i) = top
nodeList.item(i) = body
nodeList.item(i) = bottom
*/
}
}
加强1.2
//获取当前节点下面的所有节点
NodeList nodeList = documentElement.getChildNodes();
//遍历节点
for(int i=0;i<nodeList.getLength();i++){
Node item = nodeList.item(i);
//这样就可以省略掉空格了
if(item instanceof Element) {
System.out.println("nodeList.item(i) = " + item.getNodeName());
NodeList childNodes = item.getChildNodes();
for (int j = 0; j < childNodes.getLength(); j++) {
//遍历二级节点,并获取内容
System.out.println(childNodes.item(j).getTextContent().trim());
/*
输出
odeList.item(i) = top
左眼
鼻子
右眼
嘴巴
nodeList.item(i) = body
左手
胸口
右手
nodeList.item(i) = bottom
左脚
右脚
*/
}
}
}
网友评论