Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/337.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/xml/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java XML解析为列表和抓取节点_Java_Xml_Xml Parsing - Fatal编程技术网

Java XML解析为列表和抓取节点

Java XML解析为列表和抓取节点,java,xml,xml-parsing,Java,Xml,Xml Parsing,我正在解析一个XML文档,我需要将每个子节点放到一个列表中,然后一旦它在一个列表中,我就需要能够从列表中的索引中获取一个特定的子节点。到目前为止,我的代码只抓取每个子节点,但我不知道如何将其放入列表中,在其中循环似乎不起作用。以下是我到目前为止的情况: public static void main(String[] args){ DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

我正在解析一个XML文档,我需要将每个子节点放到一个列表中,然后一旦它在一个列表中,我就需要能够从列表中的索引中获取一个特定的子节点。到目前为止,我的代码只抓取每个子节点,但我不知道如何将其放入列表中,在其中循环似乎不起作用。以下是我到目前为止的情况:

public static void main(String[] args){
      DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

       try {
            URL url = new URL ("http://feeds.cdnak.neulion.com/fs/nhl/mobile/feeds/data/20140401.xml");
            URLConnection connection = url.openConnection();
            InputStream is = connection.getInputStream();
             // use the factory to create a documentbuilder
             DocumentBuilder builder = factory.newDocumentBuilder();

             // create a new document from input stream
             Document doc = builder.parse(is);        // get the first element
    Element element = doc.getDocumentElement();
    System.out.println(element);

    // get all child nodes
    NodeList nodes = element.getChildNodes();


    // print the text content of each child
    for (int i = 0; i < nodes.getLength(); i++) {
        System.out.println("" + nodes.item(i).getTextContent());
    } } catch (Exception ex) {
        ex.printStackTrace();
    }
    }

如果使用JAXB,就不需要任何循环,节点列表中已经有了节点,可以通过已经使用的节点列表方法itemint i获取任何元素。