Reputation: 99
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?
Upvotes: 1
Views: 670
Reputation: 22715
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;
}
Upvotes: 1