代码将是这样的。
private void usingDOMParser() {
try {
DocumentBuilderFactory mDocumentBuilderFactory = DocumentBuilderFactory
.newInstance();
DocumentBuilder mDocumentBuilder = mDocumentBuilderFactory
.newDocumentBuilder();
Document mDocument = mDocumentBuilder.parse(new InputSource(
getAssets().open("example.xml")));
mDocument.getDocumentElement().normalize();
NodeList mNodeList = mDocument.getElementsByTagName("child");
for (int i = 0; i < mNodeList.getLength(); i++) {
Node mNode = mNodeList.item(i);
Element mElement = (Element) mNode;
NodeList nameList = mElement.getElementsByTagName("child");
Element nameElement = (Element) nameList.item(0);
nameList = nameElement.getChildNodes();
Log.i("TAG", "ID: " + nameElement.getAttribute("ID"));
Log.i("TAG", "Name: " + nameElement.getAttribute("Name"));
Log.i("TAG", "Order: " + nameElement.getAttribute("Order"));
}
}
catch (Exception e) {
Log.e("TAG", "Exception: " + e.toString());
}
}
我把你的XML
文件放在这里,Assets folder
但如果你想从 Internet 访问它,你可以这样做。
日志
03-14 17:58:15.845: I/AllTestActivity(624): ID: 1
03-14 17:58:15.845: I/AllTestActivity(624): Name: CHILD
03-14 17:58:15.845: I/AllTestActivity(624): Order: 1
03-14 17:58:15.845: I/AllTestActivity(624): ID: 1
03-14 17:58:15.845: I/AllTestActivity(624): Name: SUB_CHILD
03-14 17:58:15.845: I/AllTestActivity(624): Order: 1
03-14 17:58:15.845: I/AllTestActivity(624): ID: 1
03-14 17:58:15.845: I/AllTestActivity(624): Name: SUB_CHILD_NODE1
03-14 17:58:15.845: I/AllTestActivity(624): Order: 01
03-14 17:58:15.845: I/AllTestActivity(624): ID: 2
03-14 17:58:15.845: I/AllTestActivity(624): Name: SUB_CHILD_NODE2
03-14 17:58:15.845: I/AllTestActivity(624): Order: 02
03-14 17:58:15.854: I/AllTestActivity(624): ID: 2
03-14 17:58:15.854: I/AllTestActivity(624): Name: CHILD2
03-14 17:58:15.854: I/AllTestActivity(624): Order: 1
03-14 17:58:15.854: I/AllTestActivity(624): ID: 1
03-14 17:58:15.854: I/AllTestActivity(624): Name: SUB_CHILD
03-14 17:58:15.854: I/AllTestActivity(624): Order: 1
03-14 17:58:15.854: I/AllTestActivity(624): ID: 1
03-14 17:58:15.854: I/AllTestActivity(624): Name: SUB_CHILD_NODE1
03-14 17:58:15.854: I/AllTestActivity(624): Order: 01
03-14 17:58:15.854: I/AllTestActivity(624): ID: 2
03-14 17:58:15.854: I/AllTestActivity(624): Name: SUB_CHILD_NODE2
03-14 17:58:15.854: I/AllTestActivity(624): Order: 02
进口:
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
我希望这可以帮助你。