我正在尝试对我的 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();
}
}