我正在尝试为我的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();
}
}
答案 0 :(得分:0)
如果您想parse XML based on some criteria,可以使用Java XPath API代替基于DOM的解析器。
答案 1 :(得分:0)
如果您希望添加过滤器,最好手动执行,使用XMLStreamReader可能会有所帮助。请按照以下步骤操作:
Transformer t=TransformerFactory.newInstance().newTransformer();
StringWriter sw=new StringWriter();
StreamResult result=new StreamResult(sw);
DOMSource d=new DOMSource(XMLdoc);
t.transform(d, result);
tring xmlstring=sw.toString();
ByteArrayInputStream bain = new yteArrayInputStream(xmlstring.getBytes());
XMLInputFactory factory1 = XMLInputFactory.newInstance();
XMLStreamReader reader = factory1.createXMLStreamReader(bain);
while(reader.hasNext())
{
reader.next();
if(reader.getEventType==XMLStreamReader.START_ELEMENT)
{
if(reader.getLocalName().equals("price"))
{
//your logic
}
}
}
希望它有所帮助..