gpt4 book ai didi

Java-XML 解析

转载 作者:行者123 更新时间:2023-12-01 10:34:47 26 4
gpt4 key购买 nike

我正在用 Java 解析 XML 以检查某个属性。我正在搜索的属性是 ERG 。我的代码无法运行。

import java.io.File;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;

public class Parser {

public static void main(String[] args){

try {
File inputFile = new File("parser.txt");
DocumentBuilderFactory dbFactory
= DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(inputFile);
doc.getDocumentElement().normalize();
System.out.println("Root element :"
+ doc.getDocumentElement().getNodeName());
NodeList nList = doc.getElementsByTagName("database");
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
String nodeAttribute = eElement.getAttribute("key");
if(nodeAttribute == "ERG"){
System.out.println("YES");
}
}
}
} catch (Exception e) {
e.printStackTrace();

}
}
}

这是我的 parser.txt

<?xml version="1.0"?>
<databases>
<database key='BC'
driver='com.micro'
url.local='456@we'
login='ses2adm'
password='12dr'
/>
<database key='SGB'
driver='com.micro'
url.local='477@jj'
login='ses2adm'
password='12yh'
/>
<database key='ERG'
driver='com.micro13'
url.local='2726@kk'
login='sdm123'
password='ghjhj'
/>
<database key='MESH'
driver='com.micro'
url.local='hgh'
login='adgvnh33'
password='hghsj'
/>
<database key='MESJ_EOM'
driver='com.micro'
url.local='jujj'
login='124hh'
password='sunn'
/>
<database key='BSUJ'
driver='com.micro'
url.local='dkl12'
login='eh23'
password='fukll'
/>
<database key='BSYH_EOM'
driver='com.micro'
url.local='skk'
login='3556'
password='eyii'
/>
</databases>

最佳答案

您正在比较references到字符串。

使用 String.equals() 方法将节点的内容与 String 进行比较。

"ERG".equals(nodeAttribute)

关于Java-XML 解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34829754/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com