我正在嘗試爲我的xml使用DOM解析器。代碼如下。它按標籤類型及其屬性(如價格和顏色)列出所有元素。然而,我很難找到如何給代碼添加限制,比如「給我所有10美元以上的筆」或「筆的顏色是黑色的名字」。有人可以幫我嗎。使用DOM解析器解析xml並添加限制
感謝
我.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();
}
}
添加XML文件在這裏爲您解決問題,這將有助於我們, – gks
你好,請找到上面更新的 – rob