Xml 中的断言

Assertion in Xml

我想在 xml 文件中找到一个特定的键,并想用该特定键的预期值断言实际值。

例如:这是一个 xml 文件,我想断言学生 ID 是否为 493, 这种情况下可以使用xmlUnit吗?或者在 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>

xmlunit 库适用于整个文件处理和匹配,但对于单个值 "native" XPath 更适合恕我直言。例如:

import org.w3c.dom.Document;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathFactory;

    Document xmlDocument = ...
    XPath xPath = XPathFactory.newInstance().newXPath();
    String expression = "/student[1]/@id";
    String actualValue = xPath.evaluate(expressiong, xmlDocument);
    assertEquals( "493", actualValue );

有关示例,请参阅 Intro to XPath with Java

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);
          }
}

我们将获取 studentList 中的所有学生,然后检查特定学生是否存在。