我有一个带有消息的 xml 文件:
<bus>
<message id="58afdb36-9080-4dd8-922e-ee516b2b5073">
<retrievedDate>Mon Feb 18 14:43:23 GMT 2013</retrievedDate>
<addedDate>Mon Feb 18 14:43:23 GMT 2013</addedDate>
<state>initialised</state>
<content>content placeholder</content>
</message>
</bus>
我正在创建一种方法来更改给定 ID 的消息状态。
但是,当我尝试获取具有所需 ID 的节点时,我不断收到 NullPointerException。尝试过使用getElementById和getElementsByTagName,但我总是得到 null 而不是我想要的节点。
public static int updateMessageState(UUID messageID, String newState)
throws ParserConfigurationException,
SAXException, IOException, TransformerException {
String filepath = "data.xml";
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.parse(filepath);
// Get Message
Node message = doc.getElementById(messageID.toString());
// Find and update the state
NamedNodeMap atrMap = message.getAttributes();
Node nodeAtr = atrMap.getNamedItem("state");
nodeAtr.setTextContent(newState);
// Save write to XML
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File(filepath));
transformer.transform(source, result);
return 0;
}