Мой код для вставки новой пары кредитов на желаемом уровне машины.
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>