使用 Java DOM 解析器,可以在 Android 上将新的 XML 内容追加到现有 XML 文件的特定标签下。

首先,需要将原始 XML 文件读取到 DOM 对象中。然后,找到要追加的标签并创建一个新的节点。将新节点添加到目标标签的子节点列表中,最后将 DOM 对象写回到文件中。

以下是一个示例代码:

import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class XmlAppender {
    public static void main(String[] args) {
        try {
            // Load the XML file into a DOM object
            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
            Document doc = dBuilder.parse(new File("input.xml"));

            // Find the target tag to append to
            NodeList targetNodes = doc.getElementsByTagName("targetTag");

            // Create a new node to append
            Element newNode = doc.createElement("newNode");
            newNode.setAttribute("attribute", "value");
            newNode.setTextContent("New node content");

            // Append the new node to the target tag
            Node targetNode = targetNodes.item(0);
            targetNode.appendChild(newNode);

            // Write the DOM object back to the XML file
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            DOMSource source = new DOMSource(doc);
            StreamResult result = new StreamResult(new File("output.xml"));
            transformer.transform(source, result);
        } catch (ParserConfigurationException | TransformerException | IOException | SAXException e) {
            e.printStackTrace();
        }
    }
}

在这个示例中,我们假设要在名为'targetTag'的标签下追加新的标签'newNode'。我们使用 Document 对象的 getElementsByTagName() 方法找到目标标签的节点列表,然后创建新的 Element 对象并设置其属性和文本内容。最后,我们将新节点附加到目标节点的子节点列表中,然后将 DOM 对象写回到 XML 文件中。

Android Java 使用 DOM 解析器追加 XML 内容到特定标签

原文地址: https://www.cveoy.top/t/topic/nwQL 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录