我试图从xml节点获取文本。代码似乎识别节点。这段代码 字符串L ="节点长度:" + nList.getLength()+"文字:" + nList.item(0).toString(); jTextArea1.setText(L);
返回:Node Length: 1 Text: [CompanyName: 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>
非常感谢任何帮助。
答案 0 :(得分:1)
在此行中,您将获得所有CompanyName
元素:
NodeList nList = xdocument.getElementsByTagName("CompanyName");
然后在for循环中循环遍历它们并调用它:
eElement.getElementsByTagName("CompanyName")
但这意味着CompanyName
嵌套CompanyName
元素,而不是CompanyName
元素。因此,您应该在for循环中使用它,因为您迭代的元素已经是String nodeTxt = "Company : " + eElement.getTextContent()
元素:
{{1}}