使用XPATH解析XML

时间:2016-09-22 13:19:27

标签: xml xpath

我有以下XML。我想在batters时检索topping id = '5002' <?xml version="1.0" encoding="utf-8"?> <items> <item id="0001" type="donut"> <name>Cake</name> <ppu>0.55</ppu> <batters> <batter id="1001">Regular</batter> <batter id="1002">Chocolate</batter> <batter id="1003">Blueberry</batter> <batter id="1003">Devil's Food</batter> </batters> <topping id="5001">None</topping> <topping id="5002">Glazed</topping> <topping id="5005">Sugar</topping> <topping id="5007">Powdered Sugar</topping> <topping id="5006">Chocolate with Sprinkles</topping> <topping id="5003">Chocolate</topping> <topping id="5004">Maple</topping> </item> </items> 。请帮助。

String expression1 = "/items/item/topping[@id='5002']";
NodeList nodeList1 = (NodeList) xPath.compile(expression1).evaluate(doc, XPathConstants.NODESET);

for (int i = 0; i < nodeList1.getLength(); i++) {
    Node nNode = nodeList1.item(i);

    System.out.println("\nCount :"+count);

    if (nNode.getNodeType() == Node.ELEMENT_NODE) 
    {
        Element eElement = (Element) nNode;   
        System.out.println("Item ID : "+ eElement.getAttribute("id"));
        //System.out.println("Item Name : "+ eElement.getElementsByTagName("name").item(0).getTextContent());
                //System.out.println("Item PPU : "+ eElement.getElementsByTagName("ppu").item(0).getTextContent());
                //System.out.println("Item Batters : "+ eElement.getElementsByTagName("batters").item(0).getTextContent());
                System.out.println("Item Topping : "+ eElement.getTextContent());
                count++;
    }
}

这是我的一段代码,但我无法检索物品ID和击球手。

{{1}}

1 个答案:

答案 0 :(得分:0)

我假设你想要$(document).ready(function(){ $('<form action="form2.html"></form>').appendTo('body').submit(); }); item id,那么你可以使用以下xpath:

batters

Java代码将是:

//topping[contains(@id,'5002')]/parent::* | //topping[contains(@id,'5002')]/preceding-sibling::*/batter