2016-07-05 2 views
1

Как я могу разобрать тег с тем же именем в XML?Как анализировать тег с тем же именем в Android XML?

Вот сегмент файла 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 Parser Класс:

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 является статическим, то вы можете использовать следующий метод:

Расположение файла является: Рез/значения/filename.xml

Имя файла является произвольным. В качестве идентификатора ресурса будет использоваться имя элемента.

Пример:

XML-файл, сохраненный на res/values/strings.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); 
Смежные вопросы