【发布时间】:2015-10-26 05:19:38
【问题描述】:
我有一个 XML 文件,我正在尝试使用 Java 进行搜索。我需要通过它的属性值(端口号)找到一个元素并返回元素的依赖描述。
已知端口的 xml 文件应该在线托管,并且具有如下架构:
<ports>
<record>
<number></number>
<name></name>
<protocol></protocol>
<description></description>
</record>
<record>
<number></number>
<name></name>
<protocol></protocol>
<description></description>
</record>
<record>
<number></number>
<name></name>
<protocol></protocol>
<description></description>
</record>
<record>
<number></number>
<name></name>
<protocol></protocol>
<description></description>
</record>
</ports>
元素没有唯一标识符。在我的应用程序中,我想调用一个带有数字作为参数的函数,它应该给我具有给定属性“数字”的项目的描述。
我的问题是,它是所有已知端口的列表,我无法手动编辑结构以分配具有端口号作为属性的所有元素。谁能告诉我如何解决这个问题?
提前致谢
更新:我想像get_port(int portno) 一样搜索它。这是我的代码:
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class DOMExampleJava {
public static void main(String args[]) {
try {
File input = new File("input.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(input);
doc.getDocumentElement().normalize();
NodeList nodes = doc.getElementsByTagName("record");
System.out.println("==========================");
for (int i = 0; i < nodes.getLength(); i++) {
Node node = nodes.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
Element element = (Element) node;
System.out.println("Port number: " + getValue("number", element));
System.out.println("Protocol: " + getValue("protocol", element));
System.out.println("Description: " + getValue("description", element));
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
private static String getValue(String tag, Element element) {
NodeList nodes = element.getElementsByTagName(tag).item(0).getChildNodes();
Node node = (Node) nodes.item(0);
return node.getNodeValue();
}
}
【问题讨论】:
-
您需要使用XML parser 来解析XML。
-
您将需要一个 XML 解析器。我个人喜欢用Jsoup
-
好的,谢谢,我知道了。我已经用我的新代码更新了我的问题。你能帮我根据属性号搜索其中的特定记录吗?
-
你试过using XPath吗?
-
问题是,如上所述,我有一个已知端口(大约 40000 个元素)的现成 xml 列表,并且它的架构也没有元素的唯一标识符。我用元素属性值而不是元素值来搜索它!所以每个元素都有 3 个属性但没有唯一标识符,我不知道如何搜索给定端口号的描述。