如何使用DOM将子元素附加到根元素。这是我的XML文件。
<?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");
}
答案 0 :(得分:0)
我认为您的代码中没有问题来操纵DOM对象。但缺少的是你需要在某处输出DOM对象,例如一份文件。否则,对象只是一些内存块,它们不会自动保留到源文件中。
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File(filepath));
transformer.transform(source, result);