Node循环中的GetElementByTagName

时间:2016-03-15 04:55:55

标签: java xml dom

我需要获得" location"的价值。元素,但我遇到了麻烦。我们的章节是关于遍历,NodeIterators和NodeFilters,我不知道如何实现它。

我需要的结果是:

  杰伊库克州立公园冬季活动

     

活动名称:Lil Park Peeps - 沉睡的熊

     

活动名称:冬季遭遇 - 雪鞋远足

我尝试了这些示例,但我在查看该XML文件的工作方式时遇到了问题。

<DEvent>
<event eid="3">Lil' Park PEEPS - Slumbering Bears</event>
<date>2/04/2016</date>
<time>10:30-11:30 AM</time>
<description>
This program series is a preschool envinromental education program designed for ages 2-5 years. Each month explores a different topic through engaging songs, stories, hands on activities and outdoor exploration
</description>
<location>Jay Cooke State Park</location>
<cost>Free</cost>
<infoPhone>218-384-4610, Ext 227</infoPhone>
<infoEmail>kris.hiller@state.mnu.us</infoEmail>
</DEvent>
<DEvent>...</DEvent>
<DEvent>
<event eid="5">Winter Encounters - Snowshoe Hike</event>
<date>2/06/2016</date>
<time>1:00-2:30 PM</time>
<description>
Join us on these snowshoe hikes to discover the park in winter to see what we encounter in the woods or along the river. Child and adult snowshoes are available
</description>
<location>Jay Cooke State Park</location>
<cost>Vehicle Permit to the Park</cost>
<infoPhone>218-384-4610, Ext. 227</infoPhone>
<infoEmail>kris.hiller@state.mn.us</infoEmail>
</DEvent>


    public class stepThrough {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        File file = new File("DNREvents.xml");
        try{
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); 
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();  
        Document doc = dBuilder.parse(file);

        NodeList eventList = doc.getElementsByTagName("DEvent");
        for (int i=0; i< eventList.getLength(); i++) { 
            Node thisNode = eventList.item(i);

            Node event = thisNode.getChildNodes().item(0).getNextSibling();
            String location = event.item(5).getNodeValue();
        }

        Recursion(doc);

        }
        catch(Exception ex){ 
            ex.printStackTrace();
        }
    }

    public static void Recursion(Node thisNode){
        int type = thisNode.getNodeType();
        String name = thisNode.getNodeName();
        String value = thisNode.getNodeValue();


            System.out.println("Event name:" + type+ name+value );



        for(Node child =thisNode.getFirstChild();
                child !=null;
                child = child.getNextSibling()){
            Recursion(child);
        }
    }
}

0 个答案:

没有答案