0
如何使用DOM將子元素追加到根元素。這是我的XML文件。如何在android中使用DOM將子元素附加到根元素?
<?xml version="1.0" encoding="utf-8"?>
<array>
<recipe>
<name>Name First</name>
<description>Description First</description>
<instruction>Instruction First</instruction>
</recipe>
<recipe>
<name>Name Second</name>
<description>Description Second</description>
<instruction>Instruction Second</instruction>
</recipe>
</array>
我想一個新的<recipe>
標籤添加爲<array>
標籤的孩子。這裏是我在這方面開發的java代碼,這段代碼正確地顯示了我的日誌消息,並且沒有錯誤,但它不會添加新的孩子,請幫助我,並確定哪裏出錯了。提前致謝。
private void addRecipeToMyRecipeFile(MyRecipeModel recipeModel)
{
MyRecipeModel mRecipe = recipeModel;
MyRecipeHandler recipeHandler = new MyRecipeHandler();
// Here I get the content of XML file as a string and convert the string in XML format
Document doc = convertRecipesFileIntoXML(recipeHandler.getContentOfMyRecipesFileFromSDCard());
Log.e("Doc", "convertRecipesFileIntoXML");
final NodeList nodes_array = doc.getElementsByTagName(TAG_ARRAY);
//We have encountered an <array> tag.
Element rootArrayTag = (Element)nodes_array.item(0);
Log.e("Element", "Array");
// <recipe> elements
Element recipe = doc.createElement(TAG_RECIPE);
rootArrayTag.appendChild(recipe);
Log.e("Element", "Recipe");
// <name> is name of recipe
Element name = doc.createElement(TAG_RECIPE_NAME);
name.appendChild(doc.createTextNode(mRecipe.getMyRecipeName()));
recipe.appendChild(name);
Log.e("Element", "Name");
// <description> is description of the recipe
Element description = doc.createElement(TAG_RECIPE_DESCRIPTION);
description.appendChild(doc.createTextNode(mRecipe.getMyRecipeDescription()));
recipe.appendChild(description);
Log.e("Element", "Description");
// <instructions> elements
Element instructions = doc.createElement(TAG_RECIPE_INSTRUCTION);
instructions.appendChild(doc.createCDATASection(mRecipe.getMyRecipeInstruction()));
recipe.appendChild(instructions);
Log.e("Element", "Instruction");
}