如何将值插入 xml 标签

How do I insert value in to xml tag

我有以下 xml 文件:

<?xml version="1.0"?>
<SMS>
    <ALERTS>
        <SNO>1</SNO> 
        <MOBILENUMBER>1234567890</MOBILENUMBER> 
        <TEXT>HI</TEXT> 
        <TIME></TIME> 
        <RESPONSEID></RESPONSEID>
    </ALERTS>       
</SMS>

我想将字符串值插入 XML 标签 (RESPONSEID)。我尝试过 setTextContent 和 setNodeValue 方法,但它们对我不起作用。

以下是我的小程序:

public void selectRecords() throws SQLException
{
    File file = new File("E:\Workspace\netbeans-workspace\DOM_Parser_Sample\MyXMLFile1.xml");
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document doc = db.parse(file);
    doc.getDocumentElement().normalize();
    NodeList nodeList = doc.getElementsByTagName("ALERTS");
    for (int s = 0; s < nodeList.getLength(); s++) 
    {
    Node firstNode = nodeList.item(s);

        if (firstNode.getNodeType() == Node.ELEMENT_NODE) 
        {
            Element eElement = (Element) firstNode;
            BufferedReader in = new BufferedReader(new InputStreamReader(httpcon.getInputStream()));
            StringBuffer response = new StringBuffer();
            while ((inputLine = in.readLine()) != null) 
            {
                    res = response.append(inputLine).toString();
            }
            in.close();
           NodeList responseList = eElement.getElementsByTagName("RESPONSEID").item(0).getChildNodes();
           responseList.item(0).setTextContent(res);
        }
    }
}

检查节点名称和值的示例代码:希望这能帮助您解决问题。

    Node alertNode = doc.getElementsByTagName("ALERTS").item(0);
    NodeList nodeList = alertNode.getChildNodes();
    for (int i = 0; i < nodeList.getLength(); i++) {

        Node node = nodeList.item(i);
        System.out.println("NodeName:" + node.getNodeName() + ":TextContent:" + node.getTextContent());
        if ("RESPONSEID".equalsIgnoreCase(node.getNodeName())) {
            node.setTextContent("RESPONSEID-1");
        }
    }

/** 只需验证设置值即可 */

    Node resNode = doc.getElementsByTagName("RESPONSEID").item(0);
    System.out.println("NodeName:" + resNode.getNodeName() + ":TextContent:" + resNode.getTextContent());

/** 将文件保存为 MyXMLFile1-test.xml*/

    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    DOMSource source = new DOMSource(doc);
    StreamResult result = new StreamResult(new File("MyXMLFile1-test.xml"));
    transformer.transform(source, result);

您只需要访问"RESPONSEID"节点并设置文本内容即可。

你只是一个小疏忽。当你执行 getElementsByTagName("RESPONSEID").item(0) 时,你会得到一个节点。您不需要该节点的子元素(没有子元素)。相反,您想直接设置该节点的文本内容。

更改代码中的两行即可:

Node responseList = eElement.getElementsByTagName("RESPONSEID").item(0);
responseList.setTextContent(res);