我正在尝试从 xml 节点获取文本。该代码似乎可以识别该节点。这段代码 String L = "节点长度:"+ nList.getLength()+ "文本:"+ nList.item(0).toString(); jTextArea1.setText(L);
返回:节点长度:1 文本:[公司名称:null]
所以看起来代码正在查找节点但没有获取值。这是整个代码块(这是我第一次发帖,所以我希望我的格式正确!)。 FOR 循环应该获取该值,但抛出 NULL 指针异常:
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
try{
//Get Document Builder
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
//Build Document
Document xdocument = builder.parse(new File("request.xml"));
xdocument.getDocumentElement().normalize();
NodeList nList = xdocument.getElementsByTagName("CompanyName");
//String L = "Node Length: " + nList.getLength()+ " Text: " + nList.item(0).toString();
//jTextArea1.setText(L);
for (int temp = 0; temp < nList.getLength(); temp++)
{
Node node = nList.item(0);
if (node.getNodeType() == Node.ELEMENT_NODE)
{
Element eElement = (Element) node;
String nodetxt= "Company : " + eElement.getElementsByTagName("CompanyName").item(0).getTextContent() ;
jTextArea1.setText(nodetxt) ;
}
}
} catch (Exception ex) {
java.util.logging.Logger.getLogger(TechKnowPOSGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
}
这是 XML 文件:
<?xml version="1.0" encoding="utf-8"?>
<RunReportQueryAction xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<CompanyName>Techknow</CompanyName>
<IntegrationLoginId>cwapitest</IntegrationLoginId>
<IntegrationPassword>cwtest123</IntegrationPassword>
<ReportName>Company</ReportName>
<!-- <Conditions></Conditions> -->
<!-- <Limit>10</Limit> -->
<!-- <Skip></Skip> -->
<!-- <OrderBy></OrderBy> -->
</RunReportQueryAction>
非常感谢任何帮助。
最佳答案
在此行中,您可以获得所有 CompanyName
元素:
NodeList nList = xdocument.getElementsByTagName("CompanyName");
然后你在 for 循环中循环它们并调用:
eElement.getElementsByTagName("CompanyName")
但这意味着 CompanyName
具有嵌套的 CompanyName
元素,但事实并非如此。因此,您应该在 for 循环中使用它,因为您正在迭代的元素已经是 CompanyName
元素:
String nodeTxt = "Company : " + eElement.getTextContent()
关于java - xml 节点上的 getTextContent 返回空指针异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27001526/