Skip to content

Instantly share code, notes, and snippets.

@foundkey
Last active November 7, 2018 05:37
Show Gist options
  • Save foundkey/fe588cbc915be3569ed124ffffb98878 to your computer and use it in GitHub Desktop.
Save foundkey/fe588cbc915be3569ed124ffffb98878 to your computer and use it in GitHub Desktop.
使用DOM方式,遍历XML文件
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