我想讀取XML數據,但我得到了一個錯誤:讀取XML文件在Java
node cannot be converted to element
問題是什麼? 這裏是整個代碼:
public class ReadXML {
public static void main(String[] args) throws Exception{
File xmlFile = new File("C:\\XML\\data.xml");
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
org.w3c.dom.Document document = documentBuilder.parse(xmlFile);
NodeList list = document.getElementsByTagName("Developer");
for (int i = 0; i < list.getLength(); i++) {
Node node = list.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
Element element = (Element) node;
System.out.println("ID: " + element.getAttribute("ID"));
System.out.println("Name: " + element.getElementsByTagName("Name").item(0).getTextConcent());
System.out.println("Surname: " + element.getElementsByTagName("Surname").item(0).getTextConcent());
System.out.println("Age: " + element.getElementsByTagName("Age").item(0).getTextConcent());
}
}
}
}
的xml文件:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<Developer Id="1">
<Name>Sahil</Name>
<Surname>Huseynzade</Surname>
<Age>21</Age>
</Developer>
<?XML版本= 「1.0」 編碼= 「UTF-8」 獨立= 「否」?> <開發者ID = 「1」>薩赫勒 Huseynzade –
Kober
' .getTextConcent()'應該是'.getTextContent()' – Jason