A below xml is received:
1
900
1
1
2
400
2
5
9
5
100
3
Please write a java program to read and parse the xml file, outputthe mobile information.
Java 打印XML
package 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");
}
}