[英]What am I doing wrong while parsing this XML
我正在嘗試解析具有以下結構的xml
這是我為解析它而編寫的代碼片段
doc.getDocumentElement().normalize();
System.out.println ("Root element: " +
doc.getDocumentElement().getNodeName());//prints GoodReadsResponse correctly
NodeList bk = doc.getElementsByTagName("book");// single all encompassing element in response
Node n= bk.item(1);// since the 0th node is id the 1st must be the title
System.out.println("Node value"+n.getLocalName());
Element e=(Element)n;
NodeList titleList= e.getElementsByTagName("title");//get the title
Element titleElem = (Element) titleList.item(1);
Node titleNode = titleElem.getChildNodes().item(0);// get the node value
book.setTitle(titleNode.getLocalName());// this prints null instead of printing Hamlet--why??
System.out.println("Title in parser"+titleNode.getLocalName());//null again
編輯:代碼中指出的問題是titleNode.getLocalName()
始終為null,而Im無法找出原因。 我已經將我的思想結構作為代碼中的注釋。 知道為什么會這樣嗎? 指針將不勝感激!
以下代碼
NodeList bk = doc.getElementsByTagName("book"); //This get All BOOKS
返回所有書籍項目的NodeList,因為您的xml中只有一本書,因此您應該遵循
Node n= bk.item(0);
在這種情況下,n = book node另外,您必須對Title做同樣的事情
NodeList titleList= e.getElementsByTagName("title");//get All titles
Element titleElem = (Element) titleList.item(0);
然后其余的代碼應該可以正常工作!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.