Java DOM パーサーと Apache JxPath を使用して XML ファイルを解析する方法の簡単な例が必要です。私は DOM パーサー技術を認識していますが、今はソースに JxPath を統合しようとしています。
ネットワークで検索しましたが、実際の例が見つかりません。
テストのために、私はこの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();
}
クラスContainer 、 DocumentContainer 、および JXPathContextについて読んだことがありますが、特定の作業例を含むいくつかのヘルプまたは Web ソースに感謝します。