【发布时间】:2019-10-12 14:08:20
【问题描述】:
我是使用 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 趟飞往日本的航班,将接下来的 2 趟航班路由到中国,然后将接下来的 2 趟航班路由到印度并循环并返回计数、大陆、位置名称、国家和重量。”所以,尽管你的标题,听起来你需要返回的不仅仅是一个整数。是哪个?
-
我想返回每个航班的整数计数,并使用它来将下一个航班路由到下一个国家,同时还返回国家名称。希望这是有道理的。
-
你的需求陈述很不清楚;如果您包含一些有代表性的输入和输出来显示您想要实现的目标,它总是会有所帮助。很明显,“保持计数”不是您的要求的一部分,出于某种原因,您认为它可能会成为您解决方案的一部分。