你需要分析你的字符串,以獲得一個Document
對象,您可以通過標籤讀取。
Here你可以找到如何解析你的字符串,然後用Document對象你能夠閱讀特定的標籤:
public void readDocument(Document doc) {
try{
NodeList nList = doc.getElementsByTagName("Event");
System.out.println("----------------------------");
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
System.out.println("\nCurrent Element :" + nNode.getNodeName());
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
System.out.println("LogTime : " + eElement.getElementsByTagName("logTime").item(0).getTextContent());
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
Source here
這是XML閱讀基本方式,但你可以直接編輯xml:
public void editDocument() {
try{
NodeList nList = doc.getElementsByTagName("Event");
System.out.println("----------------------------");
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
System.out.println("\nCurrent Element :" + nNode.getNodeName());
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
Node logTimeNode = eElement.getElementsByTagName("logTime").item(0);
String logTimeString = logTimeNode.getTextContent();
// Do some stuff with logTimeString
logTimeNode.setTextContent(logTimeString);
}
}
// write the content into xml file
String filepath = "/path/to/file.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);
} catch (Exception e) {
e.printStackTrace();
}
}