0

我是使用 Java 编程的初学者,特别是使用 Xpath 来解析 XML 文件。我正在尝试开发一个根据其权重路由航班的系统。我想要:

维护每个位置的航班计数;系统应接受位置并返回号码和国家/地区以将航班路由到。对于每 4 趟飞往日本的航班,将接下来的 2 趟航班飞往中国,然后将接下来的 2 趟航班飞往印度,然后循环返回计数、大陆、地点名称、国家和重量。

我将不胜感激任何帮助。

我可以使用 Xpath 传递和检索不同元素节点的 XML 数据。我尝试使用 SAX 和 STAX,但更喜欢这种方法,因为它在构造表达式时清晰简洁。

XML 文件示例:

<continent>
    <location name = "asia">
              <country>Japan</country>
              <code>0000011111</code>
              <weight>10</weight>
      </location>
      <location name = "asia">
              <country>China</country>
              <code>0000022222</code>
              <weight>1</weight>
      </location>
</continent>

Java 示例代码:

public static void main(String[] args) {

try {
  FileInputStream file = new FileInputStream(new File("c:/continents.xml"));

  DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();

  DocumentBuilder builder =  builderFactory.newDocumentBuilder();

  Document xmlDocument = builder.parse(file);

  XPath xPath =  XPathFactory.newInstance().newXPath();

  System.out.println("*************************");
  String expression = "/continent/location";
  System.out.println(expression);
  String name = xPath.compile(expression).evaluate(xmlDocument);
  System.out.println(name);

  System.out.println("**********Parse XML File***************");
  expression = "/continent/location/country|//number|//weight";
  System.out.println(expression);
  NodeList nodeList = (NodeList) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODESET);
  for (int i = 0; i < nodeList.getLength(); i++) {
      System.out.println(nodeList.item(i).getFirstChild().getNodeValue()); 
  }

  System.out.println("*************************");
  expression = "/continent/location[@name='asia']/number";
  System.out.println(expression);
  nodeList = (NodeList) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODESET);
  for (int i = 0; i < nodeList.getLength(); i++) {
      System.out.println(nodeList.item(i).getFirstChild().getNodeValue()); 
  }

  System.out.println("*************************");
  expression = "//location[country='China']";
  System.out.println(expression);
  Node node = (Node) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODE);
  if(null != node) {
    nodeList = node.getChildNodes();
    for (int i = 0;null!=nodeList && i < nodeList.getLength(); i++) {
      Node nod = nodeList.item(i);
      if(nod.getNodeType() == Node.ELEMENT_NODE)
        System.out.println(nodeList.item(i).getNodeName() + " : " + nod.getFirstChild().getNodeValue()); 
    }
  }
}
4

1 回答 1

0

我不确定我是否理解您的目标,但如果您只想计算飞往特定国家/地区的航班数量,您可以计算匹配元素:

NodeList matches = (NodeList) xPath.evaluate(
    "//country[text()='" + country + "']",
    xmlDocument,
    XPathConstants.NODESET);

int matchCount = matches.getLength();
于 2019-10-12T17:15:31.420 回答