如何在xml文件中比较节点?

时间:2014-04-10 06:46:32

标签: java xml

我是使用xml的新手。 我的要求是将每个节点与同一sml文件中的其他节点进行比较。

enter image description here

例如 book 是root标签子标签是作者,标题,流派,价格,publish_date 这种结构与其他节点比较如何在java中实现。并给我一些链接,如果可能的代码也。

2 个答案:

答案 0 :(得分:0)

您可以将每个元素转换为java对象POJO。然后重写equals()方法。现在您将拥有对象列表。现在迭代列表并将每个对象与每个其他对象进行比较。

答案 1 :(得分:0)

您可以使用简单的DOM Parser从XML文件中读取。阅读所有元素并将其保存到对象(书籍),然后您可以根据需要比较它们的值。以下是如何读取xml文件的示例:

import java.io.File;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class ReadXMLFile {

    public static void main(String argv[]) {

        try {
            File fXmlFile = new File("nodes.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("catalog");

            for (int temp = 0; temp < nList.getLength(); temp++) {

                Node nNode = nList.item(temp);

                System.out.println("Current Element :" + nNode.getNodeName());

                if (nNode.getNodeType() == Node.ELEMENT_NODE) {
                    Element eElement = (Element) nNode;
                    System.out.println("Author : " + eElement.getElementsByTagName("author").item(0).getTextContent());
                    System.out.println("Title : " + eElement.getElementsByTagName("title").item(0).getTextContent());
                    System.out.println("Genre : " + eElement.getElementsByTagName("genre").item(0).getTextContent());
                    System.out.println("Price : " + eElement.getElementsByTagName("price").item(0).getTextContent());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

我用这个文件测试了它:nodes.xml

<?xml version="1.0"?>
<catalog>
    <book id="1">
        <author>Author1</author>
        <title>Title1</title>
        <genre>Genre1</genre>
        <price>1</price>
    </book>
    <book id="2">
        <author>Author2</author>
        <title>Title2</title>
        <genre>Genre2</genre>
        <price>2</price>
    </book>
</catalog>

这是第一个元素的输出:

Root element :catalog
Current Element :catalog
Author : Author1
Title : Title1
Genre : Genre1
Price : 1
相关问题