[英]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.