A below xml is received:
<?xml version="1.0" encoding="UTF-8"?>
<config>
<mobilephonedate="January 2012">
<mode>1</mode>
<unit>900</unit>
<current>1</current>
<interactive>1</interactive>
</mobilephone>
<mobilephonedate="February 2011">
<mode>2</mode>
<unit>400</unit>
<current>2</current>
<interactive>5</interactive>
</mobilephone>
<mobilephonedate="December 2013">
<mode>9</mode>
<unit>5</unit>
<current>100</current>
<interactive>3</interactive>
</mobilephone>
</config>
Please write a java program to read and parse the xml file, outputthe mobile information.
Java 打印XML
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46package test; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; public class parseXML { public static void parseXml(String fileName) { try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document document = db.parse(fileName); NodeList nodeList = document.getChildNodes(); for (int i = 0; i < nodeList.getLength(); i++) { Node mobilePhone = nodeList.item(i); NodeList mobileNodeList = mobilePhone.getChildNodes(); for (int j = 0; j < mobileNodeList.getLength(); j++) { Node node = mobileNodeList.item(j); NamedNodeMap nameNodeMap = node.getAttributes(); for (int k = 0; nameNodeMap != null && k < nameNodeMap.getLength(); k++) { System.out.println(nameNodeMap.item(k).getNodeName() + ":" + nameNodeMap.item(k).getTextContent()); } NodeList employeeMeta = node.getChildNodes(); for (int k = 0; employeeMeta != null && k < employeeMeta.getLength(); k++) { System.out.println(employeeMeta.item(k).getNodeName() + ":" + employeeMeta.item(k).getTextContent()); } } } } catch (Exception e) { System.out.println(e.getMessage()); } } public static void main(String[] args) { parseXml("src/config.xml"); } }
最后
以上就是开心小虾米最近收集整理的关于Java 打印XML的全部内容,更多相关Java内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复