问题
I'm reusing existing objects generated elsewhere to unmarshall XML data coming in as a String type.
The object:
/* 3: */ import java.util.ArrayList;
/* 4: */ import java.util.List;
/* 5: */ import javax.xml.bind.annotation.XmlAccessType;
/* 6: */ import javax.xml.bind.annotation.XmlAccessorType;
/* 7: */ import javax.xml.bind.annotation.XmlElement;
/* 8: */ import javax.xml.bind.annotation.XmlRootElement;
/* 9: */ import javax.xml.bind.annotation.XmlType;
/* 10: */
/* 11: */ @XmlAccessorType(XmlAccessType.FIELD)
/* 12: */ @XmlType(name="", propOrder={"policy"})
/* 13: */ @XmlRootElement(name="MyNodeResponse")
/* 14: */ public class MyNodeResponse
/* 15: */ {
/* 16: */ @XmlElement(name="Policy")
/* 17: */ protected List<Policy> policy;
/* 18: */
/* 19: */ public List<Policy> getPolicy()
/* 20: */ {
/* 21:65 */ if (this.policy == null) {
/* 22:66 */ this.policy = new ArrayList();
/* 23: */ }
/* 24:68 */ return this.policy;
/* 25: */ }
/* 26: */ }
My unmarshalling code:
JAXBContext jc = JAXBContext.newInstance(MyNodeResponse.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
MyNodeResponse myNodeResponse = (MyNodeResponse)unmarshaller.unmarshal(new InputSource(new ByteArrayInputStream(xmlStringInput.getBytes("utf-8"))));
My input XML:
<ns2:MyNodeResponse
xmlns:ns2="mynamespace/2010/10">
<ns2:Policy>
....more data....
<ns2:Policy/>
<ns2:MyNodeResponse />
I get the following error when unmarshalling:
unexpected element (uri:"mynamespace/2010/10", local:"MyNodeResponse"). Expected elements are <{}MyNodeResponse>
What exactly does the "{ }" refer to in the error, and how do I unmarshall in a way to match what is present in the input XML and how the object is expecting?
回答1:
What the Error Message is Saying
What exactly does the "{ }" refer to in the error
In {}MyNodeRespons
the {}
portion refers to that qualified name not having the namespace URI portion set.
How to Fix It
You need to map the namespace qualification using the package level @XmlSchema
annotation:
package-info.java
@XmlSchema(
namespace = "mynamespace/2010/10",
elementFormDefault = XmlNsForm.QUALIFIED)
package example;
import javax.xml.bind.annotation.XmlNsForm;
import javax.xml.bind.annotation.XmlSchema;
For More Information
- http://blog.bdoughan.com/2010/08/jaxb-namespaces.html
来源:https://stackoverflow.com/questions/22334990/jaxb-unmarshalling-error-expected-elements-are-root