我有以下XML文件:如何在插入值,以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);
}
}
}
這個[張貼在這裏(http://stackoverflow.com/questions/7610894/how-to-insert-value-into-xml )包含一些有用的鏈接和響應。 – Rohit416 2015-03-02 05:56:26
'DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); Document doc = docBuilder.parse(inputFile); 節點messageType = doc.getElementsByTagName(「messageType」)。item(0); //零告訴xml中的順序 messageType.setTextContent(「SMS」);'即使這個例子不起作用:( – kittu 2015-03-02 06:03:09