如何在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分析器类:
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 :(得分:0)
如果xml文件中的内容为Static,则可以使用以下方法:
文件位置为: res / values / filename.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);