我需要一個簡單的示例如何使用Java DOM解析器和Apache JxPath解析XML文件。我意識到使用DOM解析器技術,但現在我試圖將JxPath整合到我的源代碼中。如何使用JxPath和DOM解析器解析XML文件
我已經在網絡中搜索,但我找不到工作示例。
爲了測試我有這樣的XML:
<?xml version="1.0" encoding="UTF-8"?>
<catalog>
<cd gender="male">
<title>Empire Burlesque</title>
<artist>Bob Dylan</artist>
<country>USA</country>
<company>Columbia</company>
<price>10.90</price>
<year>1985</year>
</cd>
<cd gender="male">
<title>Hide your heart</title>
<artist>Bonnie Tyler</artist>
<country>UK</country>
<company>CBS Records</company>
<price>9.90</price>
<year>1988</year>
</cd>
</catalog>
Java代碼:
File file = new File("Files/catalog.xml");
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
try
{
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.parse(file);
NodeList nList = doc.getElementsByTagName("cd");
for(int j = 0; j<nList.getLength(); j++){
Element element = (Element)nList.item(j);
System.out.println(element.getElementsByTagName("artist").item(0).getTextContent() + "\n");
}
}
catch (ParserConfigurationException | SAXException | IOException e)
{
e.printStackTrace();
}
我已閱讀類集裝箱,DocumentContainer和JXPathContext,但 我將不勝感激一些幫助或特定工作示例的Web源代碼。