I want to find a specific key in an xml file and want to assert the actual value with the expected value of that particular key.
for example: This is an xml file and I want to assert Student id is 493 or not, In this type of scenario can I use xmlUnit? or give other ways to do this in an easy way with help of java.
<?xml version = "1.0"?>
<class>
<student id="393">
<name>Rajiv</name>
<age>18</age>
</student>
<student id="493">
<name>Candie</name>
<age>19</age>
</student>
</class>
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;
import java.io.File;
File fXmlFile = new File("file.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
NodeList nList = doc.getElementsByTagName("student");
System.out.println("----------------------------");
List studentList = new ArrayList();
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
studentId = eElement.getAttribute("id"));
//In above we will get studentID one by one . you can add into one list and finally check expected studentid is present or not.
studentList.add(studentId);
}
}
We will get all student in studentList then check specific student is present or not.