《Java 核心技术》XML 文件解析的示例程序
参考:《Java核心技术卷II:高级特性》第7版第12章XML【完整的程序代码】
程序代码:import import 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.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class ParsingXMLDocument {
public static void main(String[] args) {
try {
parsingXMLDocument("C:/xml_file.xml");
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void parsingXMLDocument(final String XML_FILE_PATH)
throws ParserConfigurationException, SAXException, IOException {
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
File file = new File(XML_FILE_PATH);
if (!(file.exists() && file.isFile())) { return; }
Document document = documentBuilder.parse(file);
Element rootElement = document.getDocumentElement();
System.out.println("<" + rootElement.getNodeName() + ">");
NodeList rootElementChildNodeList = rootElement.getChildNodes();
for (int rootElementChildNodeIndex = 0;
rootElementChildNodeIndex < rootElementChildNodeList.getLength();
rootElementChildNodeIndex++) {
Node node = rootElementChildNodeList.item(rootElementChildNodeIndex);
if (node instanceof Element) {
Element nodeElement = (Element) node;
System.out.println("\t<" + nodeElement.getNodeName() + ">");
NodeList nodeElementChildNodeList = nodeElement.getChildNodes();
for (int nodeElementChildNodeIndex = 0;
nodeElementChildNodeIndex < nodeElementChildNodeList.getLength();
nodeElementChildNodeIndex++) {
Node childNode = nodeElementChildNodeList.item(nodeElementChildNodeIndex);
if (childNode instanceof Element) {
Element childNodeElement = (Element) childNode;
System.out.println(
"\t\t<" + childNodeElement.getNodeName() + ">" +
childNodeElement.getTextContent() +
"</" + childNodeElement.getNodeName() + ">"
);
}
}
System.out.println("\t</" + nodeElement.getNodeName() + ">");
}
}
System.out.println("</" + rootElement.getNodeName() + ">");
}
}【C:\xml_file.xml】的内容
程序代码:<?xml version="1.0" encoding="UTF-8"?>
<!-- This is a comment. -->
<root>
<node>
<key1>value1</key1>
<key2>value2</key2>
</node>
<node>
<key1>value3</key1>
<key2>value4</key2>
</node>
</root>【程序输出】
程序代码:<root>
<node>
<key1>value1</key1>
<key2>value2</key2>
</node>
<node>
<key1>value3</key1>
<key2>value4</key2>
</node>
</root>









