[英]Add and Remove Elements from XML - DOM Parser - Java
<company> <employee>
<age> 12 </age>
<name> name1</name>
</employee>
<employee>
<age> 12 </age>
<name> name1</name>
<status>active</status>
</employee>
<employee>
<age> 12 </age>
<name> name1</name>
</employee></company>
Java代碼:
employeeList nList = doc.getElementsByTagName("employee");
for (int i = 0; i < nList.getLength(); i++) {
Node employeeNode= nList.item(i);
employeeList employeeList = nNode.getChildNodes();
Node insertNode=null;
System.out.println(" Processing the " + i + " Portlet Tag");
//Inner Loop to Process each Portlet tags
int employeeList_Count=employeeList.getLength();
for (int j = 0; j < employeeList_Count; j++) {
Node childNode = employeeList.item(j);
if( childNode.getNodeName()) == "status") {
removeNode(nNode,childNode); // assume remove functionality perfectly works (actually it is!!)
}
if ( j == employeeList_Count - 2) // goes into loop during last node
{
Element insertElement = (Element)nNode;
insertElement.insertBefore(employee_status_element, insertElement.getFirstChild().getNextSibling()); //employee_status_element, this is the element should be inserted in all employee tags
doc.getDocumentElement().normalize();
updateXml2File(doc, xmlDTDPath , outputFile); // functionality to write the xml into file
}
}
}
每次我運行此代碼時,只有最后一名雇員(3名中)會使用元素“狀態”進行更新...
這是輸出的就像
第一個循環完成標簽位於第一個雇員標簽中。在第二個循環中它被推至第二個。 最后只有last元素具有status元素。
非常有幫助...非常感謝您的指導。
我已經解決了這個問題。 這很愚蠢,但是在醒了幾個小時后就被打了。
邏輯以前是這樣的
Create Element
Loop for Multiple Employees
Attach/Append the Element to Employees
問題:元素僅附加到循環中的最后一個雇員節點。
原因:由於我在循環之前僅創建了一個元素。我無法將其附加到多個員工節點
解決方案:
現在,我將創建的元素移入循環,然后開始工作。
Loop for Multiple Employees
Create Element
Attach/Append the Element to Employees
我的問題和代碼有點混亂,我試圖盡可能地對其進行糾正,以使其變得簡單,但無法執行...感謝所有嘗試解決此問題的人。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.