Last active
November 7, 2018 05:37
-
-
Save foundkey/fe588cbc915be3569ed124ffffb98878 to your computer and use it in GitHub Desktop.
使用DOM方式,遍历XML文件
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static void traversalXMLFile(String uri) throws Exception { | |
StringBuilder result = new StringBuilder(); | |
result.append("File: ").append(uri).append("\n"); | |
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); | |
DocumentBuilder db = dbf.newDocumentBuilder(); | |
Document doc = db.parse(uri); | |
Element rootElement = doc.getDocumentElement(); | |
// check root element | |
String rootTagName = rootElement.getTagName(); | |
String rootNodeName = rootElement.getNodeName(); | |
result.append("rootTagName: ").append(rootTagName) | |
.append("\trootNodeName: ").append(rootNodeName).append("\n"); | |
// check root child element; | |
traversalNode(rootElement, "", result); | |
Log.d(TAG, result.toString()); | |
} | |
private static void traversalNode(Node node, String tapStr, StringBuilder result) { | |
int childCount = node.getChildNodes().getLength(); | |
// self | |
result.append(tapStr).append("<") | |
.append(node.getNodeName()) | |
.append("\ttype: ").append(node.getNodeType()) | |
.append("\tnodeValue: ").append(node.getNodeValue()) | |
.append("\tchildCount: ").append(childCount) | |
.append(">\n"); | |
// child | |
if (childCount > 0) { | |
NodeList childList = node.getChildNodes(); | |
for (int i = 0; i < childList.getLength(); ++i) { | |
traversalNode(childList.item(i), tapStr.concat("\t"), result); | |
} | |
result.append(tapStr).append("<\\").append(node.getNodeName()).append(">\n"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment