我创建了一个XML解析器,以从XML文件中检索信息到Java,然后尝试将这些数据存储到ArrayList中,以便将ArrayList用于我的方法。当我打印它时,它似乎工作正常。但是,我有一个名为getAllRoutes的方法由于某种原因,它返回了错误的路由数
请移动
routes.add(r);
内部
if (c.getNodeName().equals("Route")) {
让我知道这是否对Khaled有所帮助。
尝试一下:
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;
import javax.xml.xpath.XPathExpressionException;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.List;
import java.util.ArrayList;
class Main {
public static Iterable<Node> iterable(final NodeList nodeList) {
return () -> new Iterator<Node>() {
private int index = 0;
@Override
public boolean hasNext() {
return index < nodeList.getLength();
}
@Override
public Node next() {
if (!hasNext())
throw new NoSuchElementException();
return nodeList.item(index++);
}
};
}
private static List<String> evaluateXPath(Document document, String xpathExpression)
{
// Create XPathFactory object
XPathFactory xpathFactory = XPathFactory.newInstance();
// Create XPath object
XPath xpath = xpathFactory.newXPath();
List<String> values = new ArrayList<>();
try
{
// Create XPathExpression object
XPathExpression expr = xpath.compile(xpathExpression);
// Evaluate expression result on XML document
NodeList nodes = (NodeList) expr.evaluate(document, XPathConstants.NODESET);
for (int i = 0; i < nodes.getLength(); i++) {
values.add(nodes.item(i).getNodeValue());
}
} catch (XPathExpressionException e) {
e.printStackTrace();
}
return values;
}
public static void main(String[] args) throws Exception {
//Build DOM
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true); // never forget this!
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse("data.xml");
//Create XPath
XPathFactory xpathfactory = XPathFactory.newInstance();
XPath xpath = xpathfactory.newXPath();
String xpathRoot = "//Routes/Route";
XPathExpression expr = xpath.compile(xpathRoot);
int i = 0;
for (Node n : iterable((NodeList) expr.evaluate(doc, XPathConstants.NODESET))) {
i++;
String xpe2 = String.format("%s[%d]/%s/text()", xpathRoot, i, "FlightNumber");
System.out.println("FxPe: " + xpe2);
System.out.println("Flight Number: " + evaluateXPath(doc, xpe2).get(0));
for (Node n2 : iterable(n.getChildNodes())) {
System.out.println(n2.getTextContent());
}
}
}
}
查看它的操作here
有用的链接:
我会说。我你的代码:Route r = new Route();
应该在if语句中if (c.getNodeName().equals("Route"))
已注释掉的添加在正确的位置-另一个位置是错误的。