繁体   English   中英

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

[英]how to compare node with each other in xml file?

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

在此处输入图片说明

例如, 是根标签,子标签是author,title,genre,price,publish_date该结构与其他节点相比,在Java中是怎么可能的。 并给我一些链接,如果可能的话还提供代码。

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

您可以使用简单的DOM解析器来读取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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM