Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/368.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在java中通过搜索从xml节点获取值_Java_Xml - Fatal编程技术网

在java中通过搜索从xml节点获取值

在java中通过搜索从xml节点获取值,java,xml,Java,Xml,我需要知道我的逻辑是否正确,因为我不熟悉XML节点。 这是我的密码。 爪哇 试试看{ File inputFile=新文件(“C:\\Users\\luenwong\\Desktop\\decoded.txt”); Scanner Scanner=new Scanner(新文件(“C:\\Users\\luenwong\\Desktop\\decoded.txt”); String text=scanner.useDelimiter(“\\A”).next(); scanner.close();

我需要知道我的逻辑是否正确,因为我不熟悉XML节点。 这是我的密码。 爪哇

试试看{
File inputFile=新文件(“C:\\Users\\luenwong\\Desktop\\decoded.txt”);
Scanner Scanner=new Scanner(新文件(“C:\\Users\\luenwong\\Desktop\\decoded.txt”);
String text=scanner.useDelimiter(“\\A”).next();
scanner.close();
DocumentBuilderFactory dbFactory=DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder=dbFactory.newDocumentBuilder();
Document docum=dBuilder.parse(inputFile);
docum.getDocumentElement().normalize();
NodeList nList=docum.getElementsByTagName(“行”);
System.out.println(“-----------------------------------”);

对于(int-temp=0;temp您应该使用
XPath
,这样您的代码将更易于阅读和维护

DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document docum = dBuilder.parse(inputFile);

XPathFactory xPathfactory = XPathFactory.newInstance();
XPath xpath = xPathfactory.newXPath();
String codeToFind = "AA02";
XPathExpression expr = xpath.compile(
    String.format("/mapping-table/row[col='%s']/col[1]", codeToFind)
);
Node node = (Node) expr.evaluate(docum, XPathConstants.NODE);
System.out.println(node.getTextContent());
输出:

KUALA LUMPUR CITY CENTRE (KLCC)
这里使用的
XPath
/mapping table/row[col='my code here']/col[1]
,这意味着我们正在寻找元素
row
的第一个子
col
,该元素有一个子
col
,其文本内容就是要查找的代码

NB:上述代码假设我们只有一个匹配项,如果您希望有多个匹配项,则需要使用下一个代码获取
节点列表,而不是
节点列表

NodeList nl = (NodeList) expr.evaluate(docum, XPathConstants.NODESET);
for (int i = 0; i < nl.getLength(); i++) {
    Node node = nl.item(i);
    System.out.println(node.getTextContent());
}
NodeList nl=(NodeList)expr.evaluate(docum,XPathConstants.NODESET);
对于(int i=0;i
它确实有效。我可以了解更多关于xPath的信息吗?因为我不太了解这行代码.String.format(“/mapping table/row[col='%s']]/col[1]”,code)。也许你能给我解释一下吗?谢谢。我会把你的答案标记为最佳答案。我在答案的末尾解释过(在NB之前),这还不够清楚?我的意思是。我必须进入确切的一行,并始终得到第一列?是的,至少这是我理解你的需要的方式,这不是你所期望的?是的。这就是我所需要的。你是我的上帝。我可以再问你一个问题吗?这是什么意思?行[col='%s']?很抱歉问了这么多,因为我试图理解,而不是复制和粘贴,所以如果需要,我可以做一些修改。
KUALA LUMPUR CITY CENTRE (KLCC)
NodeList nl = (NodeList) expr.evaluate(docum, XPathConstants.NODESET);
for (int i = 0; i < nl.getLength(); i++) {
    Node node = nl.item(i);
    System.out.println(node.getTextContent());
}