xml に DOM パーサーを使用しようとしています。コードは次のとおりです。タグの種類と価格や色などのプロパティごとにすべての要素が一覧表示されます。しかし、「10ドル以上のペンをすべてください」や「色が黒いペンの名前を教えてください」など、コードに制限を加える方法を見つけるのに苦労しました。誰か助けてくれませんか。
ありがとう
私の .xml ファイルは次のようになります。
<equipment>
<type>
<description>pen</description>
<name>parker</name>
<price value="USD">8.00</price>
<color>black</color>
</type>
<type>
<description>pen</description>
<name>ball point</name>
<price value="USD">20.00</price>
<color>purple</color>
</type>
<type>
<description>pen</description>
<name>sharpie</name>
<price value="USD">15.00</price>
<color>blue</color>
</type>
<type>
<description>pen</description>
<name>staples</name>
<price value="USD">6.00</price>
<color>red</color>
</type>
<type>
<description>pen</description>
<name>integra</name>
<price value="USD">12.00</price>
<color>white</color>
</type>
ここに私のパーサーのコードがあります
public static void main(String[] args)throws SAXException, IOException, ParserConfigurationException {
File fXmlFile = new File("docs\\abc.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
doc.getDocumentElement().normalize();
NodeList nList = doc.getElementsByTagName("type");
for(int i=0;i<nList.getLength();i++){
Node nNode = nList.item(i);
if(nNode.getNodeType() == Node.ELEMENT_NODE){
Element eElement = (Element) nNode;
System.out.println("Name:" + getTagValue("name", eElement));
System.out.println("Price: "+ getTagValue("price", eElement));
System.out.println(getAttributeValue("price", "value", eElement));
System.out.println("Description: "+getTagValue("description", eElement));
System.out.println("color:"+ getTagValue("color", eElement));
}
}
}
private static String getTagValue(String sTag, Element eElement) {
NodeList nlList = eElement.getElementsByTagName(sTag).item(0).getChildNodes();
Node nValue = (Node) nlList.item(0);
return nValue.getNodeValue();
}
private static String getAttributeValue(String sTag, String attributeName, Element eElement){
NamedNodeMap nodeMap = eElement.getElementsByTagName(sTag).item(0).getAttributes();
return nodeMap.getNamedItem(attributeName).getNodeValue();
}
}