如何在xml标记中插入值

时间:2015-03-02 05:50:39

标签: java xml domparser

我有以下xml文件:

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

我想将字符串值插入XML Tag(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);
        }
    }
}

2 个答案:

答案 0 :(得分:2)

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

    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”节点并设置文字内容。

答案 1 :(得分:1)

你只有一个小小的疏忽。执行getElementsByTagName("RESPONSEID").item(0)时,您将返回一个节点。您不希望该节点的子元素(没有子元素)。相反,您直接想要设置该节点的文本内容。

更改代码中的两行,它可以正常工作:

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