NullPointerException error when retrieving a string from an XML file

204 Views Asked by At

My title is not that great given that I'm not entirely too sure on how to word it, but the issue is that I have created the following method:

private static int createItem(Document xml) throws JDOMException, IOException{
    Element element = xml.getRootElement();
    Namespace ns = element.getNamespace();

    String itemName = xml.getRootElement().getChild("itemName", ns).getText();

    Element newItem = new Element("createItem", ns);
    newItem.addContent(new Element("shopKey", ns).addContent(key));
    newItem.addContent(new Element("itemName", ns).addContent(itemName));

    Document itemIDResponse = post("/createItem", new Document(element));
}

With the purpose of creating an item and prepping it to send it to a POST request. I have a feeling my entire method is wrong though, but it has lead me some errors which I have fixed, except now there's finally one last error left which is:

Exception in thread "main" java.lang.NullPointerException
        at TestPostRequester.createItem(TestPostRequester.java:56)
        at TestPostRequester.main(TestPostRequester.java:38)

Which highlights lines 56:

String itemName = xml.getRootElement().getChild("itemName", ns).getText();

and the method that calls createItem in my main method:

int itemID = createItem(xmlDoc);

My XML file is as follows:

<?xml version="1.0" encoding="UTF-8"?>
<items xmlns="website">
<item>
    <itemID>1</itemID>
    <itemName>CupA</itemName>
    <itemURL>none</itemURL>
    <itemPrice>50</itemPrice>
    <itemStock>15</itemStock>
    <itemDescription>
        <document>
            A <italics> beautiful and authentic</italics> cup.Containing the                  following elements:
            <list>
                <item>It's rich in history</item>
                <item>Eccentrically beautiful</item>
                <item>Organic and 100%
                                        <bold>vegan</bold>
                </item>
            </list>
    </document>
</itemDescription>

1

There are 1 best solutions below

0
On

You are missing a level in your XML heirarchy. What you have:

String itemName = xml.getRootElement()
         .getChild("itemName", ns)
         .getText();

What you should have:

String itemName = xml.getRootElement()
         .getChild("item", ns)
         .getChild("itemName", ns)
         .getText();

An XPath would work as well.... you should consider that.