コードはこのようになります。
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
が、インターネットからアクセスしたい場合は、それを行うことができます。
ログ
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;
これがあなたを助けることができることを願っています。