4

XMLノードを読み取るためのJavaコードがあります。追加で追加し、親ノードの値も読み取りたいです。

私のXMLファイルのサンプルは以下のとおりです。

 <breakfast_menu><food id=1><name> Belgian Waffles </name><price> $5.95 </price><description> two of our famous Belgian Waffles with plenty of real maple syrup </description><calories> 650 </calories></food><food id=2><name>Strawberry Belgian waffles</name><price>$7.95</price><description>light Belgian waffles covered with strawberries and whipped cream</description><calories>900</calories></food></breakfast_menu>

xmlを解析するための私のコードは:

public static String getProductItem(String pid, String item) {

    try {
        url = new URL("");
        urlConnection = url.openConnection();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {

    }

    try {
        dBuilder = dbFactory.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
    }
    try {
        doc = dBuilder.parse(urlConnection.getInputStream());
    } catch (SAXException e) {

    } catch (IOException e) {

    }

    doc.getDocumentElement().normalize();

    NodeList nList = doc.getElementsByTagName("food");

    for (int temp = 0; temp < nList.getLength(); temp++) {

        Node nNode = nList.item(temp);

        if (nNode.getNodeType() == Node.ELEMENT_NODE) {

            Element eElement = (Element) nNode;



                data = getTagValue(item, eElement);



        }
    }

    doc = null;
    dBuilder = null;

    return data;

}


private static String getTagValue(String sTag, Element eElement) {
    NodeList nlList = eElement.getElementsByTagName(sTag).item(0)
    .getChildNodes();
    Node nValue = (Node) nlList.item(0);

    return nValue.getNodeValue();
}

私がやりたいのは、食品の「id」値を読み取ることです。したがって、食品を検索する場合、IDが食品ノードIDと一致する食品ノードのみをチェックします。

タグIDで読み取ると、特に1つのタグではなく、すべてのタグが読み取られます。それを達成する方法は?

4

3 に答える 3

4

多分私は何かを逃した、それはString id = eElement.getAttribute("id");あなたが探しているだけですか?

XPathを使用してDOMからフェッチすることを検討することをお勧めします。getElementsByTagNameには、ドキュメント構造を無視するという苛立たしい習慣があります。(また、名前空間とgetElementsByTagNameNSを使用する必要があります:))

于 2010-05-11T08:06:30.557 に答える
4

XPathを使用すると、いくつかの基準に従ってノードのセットを簡単に見つけることができます。例えば:

XPath xpath = XPathFactory.newInstance().newXPath();
NodeList nl = (NodeList) xpath.evaluate("//food[@id=22]", doc, XPathConstants.NODESET);

このコードは、ドキュメント内の特定のIDを持つすべての食品ノードを検索します。XPathは、この種の検索条件のための豊富な言語です。

于 2010-05-11T08:13:01.450 に答える
3

XPathは、APIレベル8以降Androidで使用できます。XPathがオプションである場合は、xmlが次の場所のプロジェクトに配置されているとします。

/res/raw/food_list.xml

その場合、次のxpath構文を使用してすべての要素を検索できます。

//food/@id

上記の検索式は、ルート以降の要素idに関連するすべての属性のリストを返します。<food>

したがって、これらすべてのid属性をフェッチする必要がある場合は、次のように実行できます。

InputStream is = getResources().openRawResource(R.raw.food_list);
DocumentBuilderFactory fac = DocumentBuilderFactory.newInstance();

try {
    Document doc = fac.newDocumentBuilder().parse(is);
    XPath xpath = XPathFactory.newInstance().newXPath();
    XPathExpression expr;
    try {
         expr = xpath.compile("//food/@id");
         NodeList nl = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
         for (int i = 0; i < nl.getLength(); i++) {
              Node node = nl.item(i);
               // Considering the example XML at the end of this loop you will 
               // get the ids printed
              System.out.println(node.getNodeValue());
         }
    } catch (XPathExpressionException e) {
         e.printStackTrace();
    }
    is.close();
} catch (IOException e1) {
    e1.printStackTrace();
} catch (SAXException e) {
    e.printStackTrace();
} catch (ParserConfigurationException e) {
    e.printStackTrace();
}

XPath構文のクイックリファレンスと少しの説明はここにあります。

于 2012-12-05T23:18:04.673 に答える