我有以下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
}
}
答案 0 :(得分:1)
试试这个:
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();
}
}
}
答案 1 :(得分:0)
请参阅NodeList对象
的文档调用node=doc.getElementsByTagName("state");
返回一个NodeList对象,该对象具有方法item(int index)
作为元素访问方法。
试试这个:
for(int i=0;i<size;i++)
{
Node n = node.item(i);
//do you thing here
}
答案 2 :(得分:0)
您可以使用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
...
答案 3 :(得分:0)
流媒体解决方案:
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());
}
}