如何仅迭代该节点并获取值

How iterate only that node and get the values

我有以下 XML,其中我有某些节点。我必须获得状态节点的值。由于状态节点多次出现,我必须检查它出现了多少次并按节点顺序获取值。

> <?xml version="1.0" encoding="UTF-8"?> 
>         <Country>       
>             <name>India</name>
>             <capital>New Delhi</capital>
>             <population>120crores</population>
>         .
>         .
>         .
>         .
>         .
>     
>     <states>
>         <state>
>             <name>Maharastra</name>
>             <pincode>xyzzzz</pincode>
>             <capital>Mumbai</capital>
>     
>         <\state>
>     
>         <state>
>         .
>         .
>         .
>         </state>
>     </states>
>     
>     
>        <\Country>

我有以下代码部分,我将在其中检查节点长度,但我不知道如何对其进行迭代。

>     DocumentBuilderFactory dof=DocumentBuilderFactory.newInstance();
>       DocumentBuilder db=dof.newDocumentBuilder();
>       org.w3c.dom.Document doc=db.parse(new InputSource(new StringReader(statestring)));
>       node=doc.getElementsByTagName("state");

{
            int size=node.getLength();

            for(int i=0;i<size;i++)
            {
                //how to put the logic here     
            }


        }

请参阅 NodeList 对象的文档

调用 node=doc.getElementsByTagName("state"); returns 具有方法 item(int index) 作为元素访问方法的 NodeList 对象。

试试这个:

        for(int i=0;i<size;i++)
        {
            Node n = node.item(i);
            //do you thing here
        }

试试这个:

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;
import java.io.File;

public class ReadXMLFile {

  public static void main(String argv[]) {

    try {

    File fXmlFile = new File("c://input.xml");
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
    Document doc = dBuilder.parse(fXmlFile);
    doc.getDocumentElement().normalize();

    System.out.println("Root element :" + doc.getDocumentElement().getNodeName());

    NodeList nList = doc.getElementsByTagName("state");

    System.out.println("----------------------------");

    for (int temp = 0; temp < nList.getLength(); temp++) {

        Node nNode = nList.item(temp);

        System.out.println("\nCurrent Element :" + nNode.getNodeName());

    if (nNode.getNodeType() == Node.ELEMENT_NODE) {

            Element eElement = (Element) nNode;
            System.out.println("Name : " + eElement.getElementsByTagName("name").item(0).getTextContent());
            System.out.println("pincode : " + eElement.getElementsByTagName("pincode").item(0).getTextContent());
            System.out.println("capital : " + eElement.getElementsByTagName("capital").item(0).getTextContent());
        }
    }
    } catch (Exception e) {
    e.printStackTrace();
    }
  }

}

您可以使用 xpath:

    Document doc = DocumentBuilderFactory.newInstance()
            .newDocumentBuilder().parse(new InputSource(inputFile));

    // Locate the node(s) with xpath
    XPath xpath = XPathFactory.newInstance().newXPath();
    NodeList nodes = (NodeList)xpath.evaluate("//state/*", 
                                              doc, XPathConstants.NODESET);

    for (int idx = 0; idx < nodes.getLength(); idx++) {
        Node n = nodes.item(idx);
        System.out.println(n.getNodeName() + " -> " + n.getTextContent());
    }

应打印:

name -> Maharastra
pincode -> xyzzzz
capital -> Mumbai
...

流媒体解决方案:

import java.io.IOException;
import java.text.ParseException;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import java.util.List;
import java.util.ArrayList;

public class StateParser extends DefaultHandler {

    private String tmpValue;
    private State state;
    List<State> stateList = new ArrayList<State>();

    public StateParser(String xmlFileName) {
        try {
            SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
            parser.parse(xmlFileName, this);
        }
        catch (ParserConfigurationException | SAXException | IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
        if (qName.equals("state")) { state = new State(); }
    }

    @Override
    public void endElement(String uri, String localName, String qName) throws SAXException {
        if (null != state) {
            if (qName.equals("name")) { state.name = tmpValue; }
            if (qName.equals("pincode")) { state.pincode = tmpValue; }
            if (qName.equals("capital")) { state.capitol = tmpValue; }
            if (qName.equals("state")) {
                stateList.add(state);
                state = null;
            }
        }
    }

    @Override
    public void characters(char[] ac, int i, int j) throws SAXException {
        tmpValue = new String(ac, i, j);
    }

    private class State {
        String name;
        String pincode;
        String capitol;
        @Override public String toString() {
            return String.format("{name: %s, pincode: %s, capitol: %s}", name, pincode, capitol);
        }
    }

    public static void main(String[] args) {
        StateParser sp = new StateParser("states.xml");
        StringBuilder sb = new StringBuilder();
        for (State s : sp.stateList) { sb.append(s).append("\n"); }
        System.out.println(sb.toString());
    }

}