【问题标题】:Appending XML data to an ArrayList将 XML 数据附加到 ArrayList
【发布时间】:2020-04-15 16:21:06
【问题描述】:

我创建了一个 XML 解析器来将信息从 XML 文件检索到 java,然后我尝试将这些数据存储到 ArrayList 中,以便将 ArrayList 用于我的方法。 当我打印它时,它似乎工作正常。但是,我得到了一个名为 getAllRoutes 的方法 由于某种原因它返回了错误的路由数量

【问题讨论】:

  • 请添加示例您如何使用方法 getAllRoutes()
  • 有一个marker负责运行和测试我的方法,并给我每个方法的反馈,getAllRoutes()的反馈;是:测试失败,因为加载数据后getAllRoutes()返回了错误的路由数 @Daniyar

标签: java xml arraylist multidimensional-array xml-parsing


【解决方案1】:

请移动

routes.add(r);

里面

if (c.getNodeName().equals("Route")) {

【讨论】:

  • 已经抛出这个异常java.lang.NullPointerException
  • 另外请查看stackoverflow.com/questions/20259742/…,了解为什么元素有4个子元素
  • 如果你得到 NullPointerException,请分享
  • 有一个标记可以测试我的代码,这就是它所说的“测试失败,因为 RouteDAO 引发了异常:java.lang.NullPointerException”
  • 该行可能抛出 NullPointerException 的唯一方法是 如果 routes 为 null,但这里不是这种情况,因为我们在声明本身 routes时进行了初始化>
【解决方案2】:

如果这对 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")) 注释掉的添加在正确的位置 - 另一个位置是错误的。

【讨论】:

  • 我试过包括 Route r = new Route();在 if 语句中但那不起作用,现在它说 在运行该方法时返回了错误的路由数量 这意味着它实际上返回了一个数字但由于某种原因它是错误的,而如果我取消注释评论 routes.add(r); 即使在我尝试了你上面建议的在 if 语句中包含新路由 @JGFMK 之后,它也会由于某种原因引发空指针异常
  • 我尝试了您的 XPath 方法,它工作正常,但是,您将其填充到我的 ArrayList 中的最佳方法是什么,以便我可以将它用于 getAllRoutes();方法?
  • 您可以在外循环中创建一个新的路由对象,填充路由对象的所有属性,使用属性名称数组,为每个属性构建 xpath 表达式。然后,当所有属性都分配给路由对象时,将其添加到路由集合中。每次处理 XML 时,我都会倾向于生成一个新的 ArrayList。也许这就是原始代码中的问题所在。在您的原始帖子中,您注释掉的 add 方法是正确的位置。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-09-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-25
  • 1970-01-01
  • 2017-01-18
相关资源
最近更新 更多