1

I am trying to parse an xml through JAXB which contains xmlns attribute. If I parse the xml as such it shows NullPointerException. But if I remove namespace tags and xmlns attributes then it worked fine. Sample xml is as follows:

<?xml version="1.0" encoding="utf-8"?>

<database xmlns="http://www.Example/Database" xmlns:layout="http://www.Example/Layouter">
    <namespace name="X1">
        <layout:record name="My_Layout" src="screen1.layout" />
    </namespace>

    <LayoutGroup xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:xsd="http://www.w3.org/2001/XMLSchema" LayoutGroupID="ID_1">
    </LayoutGroup>
</database>

and my sample code is as follows:

@XmlRootElement(name = "database")
public class database {

    private LayoutGroup layoutGrp;

    @XmlElement(name = "LayoutGroup")
    public void setLayoutGrp(LayoutGroup gp) {
        layoutGrp = gp;
    }

    public LayoutGroup getLayoutGroup() {
        return layoutGrp;
    }

}

Another class:

@XmlRootElement (name="LayoutGroup")
public class LayoutGroup {

    String id;
    @XmlAttribute (name="LayoutGroupID")
    public void setId(String id)
    {
        this.id = id;
    }
    public String getId()
    {
        return id;
    }
}

Here's my main method:

public static void main(String[] args) {

    database db = JAXB.unmarshal(new File("./res/test.xml"),database.class);
    System.out.println("Layout id is: "+db.getLayoutGroup().getId());
}

Could anyone please help to parse the original xml?

1

1 Answer 1

1

Since you're feeding your class an XML scoped with a namespace, you should also declare it in your receiving class.

Add this line on top of your class:

@XmlRootElement (name="database") 
@XmlType(namespace="http://www.Example/Database")
public class Database {

If it still gives an error, try adding the namespace definition in your LayoutGroup element and see if it works:

@XmlElement (name="LayoutGroup", namespace="http://www.Example/Database")
public void setLayoutGrp(LayoutGroup gp)
{
    layoutGrp = gp;
}
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for replying. I tried both the solutions but still it gives NullPointerException.
Can u share the exception stacktrace in the question?
Sorry if my questions is a silly one. I just want to parse the above xml through JAXB but I am getting an error. I dont know why exactly xmlns and xmlns:layout in above xml is used for and if I have to pare such an xml then how should I go about.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.