1
我的代碼在所需的機器級別插入新的信譽對。在xml中使用dom4j在指定位置添加新節點
Document insertNewNode(String loginId,String pass,String machine_name)
{
List<?> list1 = document.selectNodes("//machine/@name");
Iterator<?> itr=list1.iterator();
while(itr.hasNext()){
Attribute attribute=(Attribute)itr.next();
if(attribute.getValue().equals(machine_name))
{
List<?> list1 = document.selectNodes("//machine");
Iterator<?> iter=list.iterator();
while(iter.hasNext()){
Element credPairs=(Element)iter.next();
Element credPair =credPairs.addElement("cred-pair");
Element login =credPair.addElement("login");
element.setText(loginId);
Element password =credPair.addElement("password");
element.setText(pass);
}
}
}
}
原始的XML:
<credentials>
<machine name="xyz">
<cred-pairs>
<cred-pair>
<login>asad</login>
<password>12345</password>
</cred-pair>
<cred-pairs>
</machine>
<machine name="pqr">
<cred-pair>
<cred-pair>
<login>ssdas</login>
<password>12345</password>
</cred-pair>
<cred-pairs>
</machine>
</credentials>
如果我打電話insertNewNode(GGSS,97653,XYZ)
預期的XML:
<credentials>
<machine name="xyz">
<cred-pairs>
<cred-pair>
<login>asad</login>
<password>12345</password>
</cred-pair>
**<cred-pair>
<login>ggss</login>
<password>97653</password>
</cred-pair>**
<cred-pairs>
</machine>
<machine name="pqr">
<cred-pair>
<cred-pair>
<login>ssdas</login>
<password>12345</password>
</cred-pair>
<cred-pairs>
</machine>
</credentials>
但我正在逐漸輸出:
<credentials>
<machine name="xyz">
<cred-pairs>
<cred-pair>
<login>asad</login>
<password>12345</password>
</cred-pair>
** <cred-pair>
<login>ggss</login>
<password>97653</password>
</cred-pair>**
<cred-pairs>
</machine>
<machine name="pqr">
<cred-pair>
<cred-pair>
<login>ssdas</login>
<password>12345</password>
</cred-pair>
**<cred-pair>
<login>ggss</login>
<password>97653</password>
</cred-pair>
<cred-pairs>**
</machine>
</credentials>
感謝lot..You救了我day..Andreas_D – user896456