0

如何使用 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");

    }
4

1 回答 1

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);
于 2013-10-30T09:47:31.803 回答