爲了插入新節點(一個或多個),你應該使用Node#insertBefore()
而不是Node#appendChild()
。檢查文檔here。
更換
Node emp=myDocument.createElement("Emp");
Text NodeText = myDocument.createTextNode("DD");
emp.appendChild(NodeText);
myDocument.appendChild(emp);
與
Node emp=myDocument.createElement("Emp");
Text NodeText = myDocument.createTextNode("DD");
emp.appendChild(NodeText);
myDocument.insertBefore(emp, someExistingNode);
凡someExistingNode是Node
(可能Element
)要添加新的Node
EMP之前這。
編輯1:如何編寫XML提交
try {
String filePath = "file:///store/home/user/XmlFile.xml";
FileConnection fc = (FileConnection) Connector.open(filePath, Connector.READ_WRITE);
if (!fc.exists()) {
fc.create(); // create the file if it doesn't exist
} else {
fc.truncate(0); // truncate the file if it exists
}
OutputStream os = fc.openOutputStream();
XMLWriter xmlWriter = new XMLWriter(os);
xmlWriter.setPrettyPrint();
DOMInternalRepresentation.parse(myDocument, xmlWriter);
os.close();
fc.close();
} catch (Exception e) {
// Place exception handling code here
}
編輯2:節點插入和XML到文件中寫入
try {
// Creating document
Document myDocument = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
Element parentElement = myDocument.createElement("parentTag");
// create first element and append it to parent
Element firstElement = myDocument.createElement("firstElement");
firstElement.appendChild(myDocument.createTextNode("1"));
parentElement.appendChild(firstElement);
// create third element and append it to parent
Element thirdElement = myDocument.createElement("thirdElement");
thirdElement.appendChild(myDocument.createTextNode("3"));
parentElement.appendChild(thirdElement);
// create second element and insert it between first and third elements
Element secondElement = myDocument.createElement("secondElement");
secondElement.appendChild(myDocument.createTextNode("2"));
parentElement.insertBefore(secondElement, thirdElement);
myDocument.appendChild(parentElement);
// Writing document to file
String filePath = "file:///store/home/user/XmlFile.xml";
FileConnection fc = (FileConnection) Connector.open(filePath, Connector.READ_WRITE);
if (!fc.exists()) {
fc.create(); // create the file if it doesn't exist
} else {
fc.truncate(0); // truncate the file if it exists
}
OutputStream os = fc.openOutputStream();
XMLWriter xmlWriter = new XMLWriter(os);
xmlWriter.setPrettyPrint();
DOMInternalRepresentation.parse(myDocument, xmlWriter);
os.close();
fc.close();
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
}
添加的代碼示例還檢查this question關於在BlackBerry上創建XML。
謝謝MrVincenzo ..你的回答幫了我很多.. :) – Reham 2012-02-18 13:53:37
但我該如何刪除節點? – Reham 2012-02-18 14:25:05
歡迎@Reham。你可以用'Node#removeChild()'方法刪除Node。例如,你可以調用'parentElement.removeChild(firstElement);'去除我的示例代碼中的** firstElement **。 – mrvincenzo 2012-02-18 14:44:12