1

Android 開発者の Web サイトで説明されているように、デバイスの内部ストレージに xml ファイルを作成しました。DOMパーサーを使用してファイルを解析したいと思います。DOM パーサーが XML ファイルを読み取れるようにするには、どうすればよいですか?? ここにスニペットがあります:

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document dom = db.parse(new InputSource(new StringReader(data)));
    dom.getDocumentElement().normalize(); 

「データ」の代わりに何を入れる必要がありますか:

    Document dom = db.parse(new InputSource(new StringReader(data)));

私はそれがばかげていることを知っていますが、助けていただければ幸いです。

4

4 に答える 4

1

XMLファイルを読むには、以下を試してください。

FileInputStream in = new FileInputStream("/sdcard/text.txt");
StringBuffer data = new StringBuffer();
InputStreamReader isr = new InputStreamReader(in);

BufferedReader inRd = new BufferedReader(isr);

String text;
while ((text = inRd.readLine()) != null) {
    inLine.append(text);
    inLine.append("\n");
}
in.close();

String finalData =data.toString();  // Here is your data.

上記がお役に立てば幸いです。

于 2012-01-10T10:33:11.383 に答える
1

入力ソースで FileInputStream を指定できます

ドキュメント dom = db.parse(new InputSource(new FileInputStream(data)));

于 2012-01-10T10:21:52.780 に答える
1

以下のように xml 文字列の入力ストリームを作成し、解析して値を取得できるノードを取得できます。

InputStream is = new ByteArrayInputStream(theXMLString.getBytes("UTF-8"));

        // Build XML document
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document doc = db.parse(is);

xml ファイルを文字列として渡していることに注意してください。

于 2012-01-10T10:29:45.910 に答える
0

DOM Parser を使用して Asset フォルダーから解析するには、次のコードを試してください。

    DocumentBuilderFactory DBF;
    DocumentBuilder DB;
    Document dom;
    Element elt;

    DBF = DocumentBuilderFactory.newInstance();
    DB = DBF.newDocumentBuilder();
    dom = DB.parse(new InputSource(getAssets().open("city.xml")));
    elt = dom.getDocumentElement(); 
    NodeList items = elt.getElementsByTagName("item");

item は Node 要素で、要件に従って try ctch ブロックを追加します。

于 2012-01-10T11:06:17.457 に答える