2

私は Java で XML 読み取りの例を探していましたが、典型的なスキーマのルート -> 3 つの等しい息子 -> 3 つの等しい孫を常に見つけます。

しかし、書籍{タイトル、著者、ページ数}を含むライブラリのように保存されていない要素のペアを取得する必要がある場合があります。私のXMLは次のようになります:

<?xml version="1.0" encoding="UTF-8" ?>
<A>
    <Crap1>
        <CrapSon>1</CrapSon>
    </Crap1>
    <B>
        <Crap2>Store</Crap2>
        <C>
            <Type>N</Type>
            <D>
                <InterestingData1>Data</InterestingData1>
            </D>
            <InterestingData2>More Data</InterestingData2>
        </C>
    </B>
</A>

もちろん、すべてを反復して、最終的に目的のデータ要素に到達することもできます。しかし、ツリーを繰り返し処理せずに、必要な要素にアクセスする高速な方法はありますか? 名前だけで検索させますか?

4

3 に答える 3

1

次のようなことを試すことができます。

import java.io.IOException;
import java.io.StringReader;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

class Test {    

    public static void main(String args[]) throws ParserConfigurationException, SAXException, IOException{
        String xmlString ="<A>" +
                "<Crap1><CrapSon>1</CrapSon>" +
                "</Crap1>" +
                "<B>" +
                "<Crap2>Store</Crap2><C><Type>N</Type><D><InterestingData1>Data</InterestingData1></D><InterestingData2>More Data</InterestingData2></C>" +
                "</B>" +
                "</A>";

        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();      
        DocumentBuilder docBuilder = dbf.newDocumentBuilder();
        Document doc = docBuilder.parse(new InputSource(new StringReader(xmlString)));

        NodeList nodelist = doc.getElementsByTagName("InterestingData2");
        NodeList nodelist2 = doc.getElementsByTagName("Type");

        String str = nodelist.item(0).getTextContent();
        String str2 = nodelist2.item(0).getTextContent();

        System.out.println("InterestingData2: "+str);
        System.out.println("Type: " + str2);
    }
}

出力:

InterestingData2: その他のデータ

タイプ: N

于 2013-01-10T14:00:14.407 に答える
1

Java SE 5 以降でライブラリを使用し、javax.xml.xpathXPath を使用して必要なデータのドキュメントをクエリできます。

于 2013-01-10T12:32:02.563 に答える
0

InterestingData1DOM が必要ない場合は、SAX パーサーと処理用のハンドラーを使用する必要があると思いますInterestingData2

于 2013-01-10T12:30:40.737 に答える