2016-07-05 6 views
1

XMLで同じ名前タグを解析するにはどうすればよいですか?Android XMLで同じ名前のタグを解析するにはどうすればよいですか?

<?xml version="1.0" encoding="utf-8"?> 
<item> 
    <RecipeDescription>A much requested chicken recipe! Easy to double for a large group. Delicious</RecipeDescription> 

    <RecipeIngredientsName>1 tablespoon cornstarch</RecipeIngredientsName> 
    <RecipeIngredientsName>1 tablespoon cold water</RecipeIngredientsName> 
    <RecipeIngredientsName>1/2 cup white sugar</RecipeIngredientsName> 
</item> 

私のXMLパーサクラス::ここで

は、XMLファイルのセグメントの

private void ProcessXml(Document data) { 
    if (data != null) { 
     recipesItems =new ArrayList<>(); 
     Element root = data.getDocumentElement(); 
     Node channel = root.getChildNodes().item(1); 
     NodeList items = channel.getChildNodes(); 

     for (int i = 0; i < items.getLength(); i++) { 
      Node cureentchild = items.item(i); 

      if (cureentchild.getNodeName().equalsIgnoreCase("item")) { 
       RecipesItem item = new RecipesItem(); 
       NodeList itemchilds = cureentchild.getChildNodes(); 

       for (int j = 0; j < itemchilds.getLength(); j++) { 
        Node cureent = itemchilds.item(j); 
        if (cureent.getNodeName().equalsIgnoreCase("RecipeDescription")) { 
         item.setRecipeDescription(cureent.getTextContent()); 
        }else if (cureent.getNodeName().equalsIgnoreCase("RecipeIngredientsName")){ 
         item.setRecipeIngredientsName(cureent.getTextContent()); 
        } 

       } 
       recipesItems.add(item); 
      } 
     } 
    } 
} 

public Document Getdata() { 
    try { 
     url = new URL(address); 
     HttpURLConnection connection = (HttpURLConnection) url.openConnection(); 
     connection.setRequestMethod("GET"); 
     InputStream inputStream = connection.getInputStream(); 
     DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); 
     DocumentBuilder builder = builderFactory.newDocumentBuilder(); 
     Document xmlDoc = builder.parse(inputStream); 
     return xmlDoc; 
    } catch (Exception e) { 
     e.printStackTrace(); 
     return null; 
    } 
} 

しかし、問題は、アイテムの同じRecipeIngredientsName名前です。これらの値を取得するにはどうすればよいですか? ありがとうございます。

答えて

0

xmlファイルの内容は静的であるなら、あなたは、次の方法で使用することができます。

ファイルの場所を次のとおりです。RES /値/ファイル名.xml

ファイル名は任意です。要素の名前がリソースIDとして使用されます。

例:res/values/strings.xmlに保存

XMLファイル:

<?xml version="1.0" encoding="utf-8"?> 
<resources> 
    <string-array name="planets_array"> 
     <item>Mercury</item> 
     <item>Venus</item> 
     <item>Earth</item> 
     <item>Mars</item> 
    </string-array> 
</resources> 

このアプリケーションコードは、文字列配列を取得します

Resources res = getResources(); 
String[] planets = res.getStringArray(R.array.planets_array); 
関連する問題