簡體   English   中英

無法在java中讀取XML文件?

[英]Trouble reading an XML file in java?

所以我在閱讀這個XML文件時遇到了很多麻煩:

<?xml version = "1.0" encoding = "UTF-8"?>
<!--this version of Eclipse dosn't support direct creation of XML files-->
<!-- you have to create one in notepad and then copy/paste it into Eclipse-->

<root testAttribute = "testValue">
    <data>Phoebe</data>
    <data>is</data>
    <data>a</data>
    <data>puppy!</data>

    <secondElement testAttribute = "testValueAgain">
        <data2>Poop</data2>
        <data2>Doopy</data2>
    </secondElement>
</root>

在我的java文件中,我在這一行中得到一個NullPointerException。 這是代碼:(我會指出發生異常的地方)

import javax.xml.parsers.*;
import org.w3c.dom.*; 
import org.xml.sax.*;

import java.io.*;

public class Reading {
    public static void main(String args[]){
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        try {
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document doc = builder.parse(new File("res/Test.xml"));

            ////////////////////GET ELEMENTS//////////////////

            Element rootElement = doc.getDocumentElement(); 
            System.out.println("Root element: " + doc.getDocumentElement().getNodeName());
            System.out.println("testAttribute for root element: "
                + rootElement.getAttribute("testAttribute"));

            Element secondElement = doc.getElementById("secondElement");
            System.out.println("testAttribute for second element: " + 
                secondElement.getAttribute("testAttribute")); //THIS IS THE LINE

            NodeList list = rootElement.getElementsByTagName("data");

            NodeList list2 = rootElement.getElementsByTagName("data2");

            //////////////////////////////////

            for(int i = 0; i < list.getLength(); i++){
                Node dataNode = list.item(i);
                System.out.println("list index: " + i + " data at that index: " +
                dataNode.getTextContent());
            }

            for(int i = 0; i < list2.getLength(); i++){
                Node dataNode = list2.item(i);
                System.out.println("list2 index: " + i + " data at that index: " +
                dataNode.getTextContent());
            }
        }catch(ParserConfigurationException e){
            e.printStackTrace();
        }catch(IOException e){
            e.printStackTrace();
        }catch(SAXException e){
            e.printStackTrace();
        }
    }
}

你們可以查看我的代碼並告訴我如何避免NullPointerException? 我現在真的很沮喪。 謝謝!

PS你們中的一些人回答了有關異常的線上方的線路。 當我嘗試在secondaryElement元素中打印出testAttribute值時發生異常。

getElementByID不是你想象的那樣,因此返回null(沒有id =“...”屬性)。

快速回答是你的secondElement為null。 原因是因為你沒有id="secondElement"元素。 您的代碼希望文檔包含類似的內容

<myelement id="secondElement">...</myelement>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM