如何与 XML 结构进行比较,忽略标签内容?
例如,以下响应:
<note>
<to>Adam</to>
<from>Eve</from>
</note>
并且:
<note>
<to>John</to>
<from>Joan</from>
</note>
具有相同的 XML 结构,但是:
<note>
<from>Joan</from>
<to>John</to>
</note>
与第一个示例不同,因为标签的顺序不同。
如何比较 Java 中的 XPath 结构?
最佳答案
您可以使用 JAVA DOM 解析器或 SAX 解析器
下面是访问元素的示例,之后您需要进行正常比较
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;
public class ReadXMLFile {
public static void main(String argv[]) {
try {
File fXmlFile = new File("/Input.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
doc.getDocumentElement().normalize();
System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
NodeList nList = doc.getElementsByTagName("staff");
System.out.println("----------------------------");
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
System.out.println("\nCurrent Element :" + nNode.getNodeName());
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
System.out.println("Note: " + eElement.getAttribute("note"));
System.out.println("From: " + eElement.getElementsByTagName("from").item(0).getTextContent());
System.out.println("To : " + eElement.getElementsByTagName("to").item(0).getTextContent());
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
关于java - 比较两个 XML 文件的结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16261391/