我正在尝试使用 JAXB 解组 xml 文件。当我使用具有正确名称和命名空间的@XmlElement 时,解组工作(例如@XmlElement(name = "name", namespace="http://www.test.com"))
如果我将 XmlType 与 propOrder 一起使用,不幸的是它不再使用了(例如 @XmlType(namespace="http://www.test.com", name = "", propOrder = {"name", "description"}))。
xml文件(test.xml)的内容:
<Operation xmlns="http://www.test.com">
<Parameter>
<name>Param1</name>
<description>Description of Parameter1</description>
</Parameter>
<Parameter>
<name>Param2</name>
<description>Description of Parameter2</description>
</Parameter>
</Operation>
JAXBExample.java 的内容是:
package stackoverflow.problem.jaxb.ns;
import java.io.FileNotFoundException;
import java.io.FileReader;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
public class JAXBExample {
public static void main(String[] args) throws JAXBException, FileNotFoundException {
String xmlFilename = "test.xml";
JAXBContext context = JAXBContext.newInstance(Operation.class);
System.out.println("Output from our XML File: ");
Unmarshaller um = context.createUnmarshaller();
Operation op = (Operation) um.unmarshal(new FileReader(xmlFilename));
System.out.println("Operation-Content: " + op);
}
}
的内容
包stackoverflow.problem.jaxb.ns;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name="Operation", namespace="http://www.test.com")
@XmlAccessorType(XmlAccessType.FIELD)
public class Operation {
@XmlElement(name = "Parameter", namespace="http://www.test.com")
List<Parameter> parameterList;
@Override
public String toString(){
String retVal = "";
for(Parameter currentParameter: parameterList){
retVal += currentParameter.toString() + "\n";
}
return retVal;
}
}
Parameter.java 的内容是:
package stackoverflow.problem.jaxb.ns;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
@XmlType(namespace="http://www.test.com", name = "", propOrder = {"name", "description"})
@XmlAccessorType(XmlAccessType.FIELD)
public class Parameter {
//@XmlElement(name = "name", namespace="http://www.test.com")
String name;
//@XmlElement(name = "description", namespace="http://www.test.com")
String description;
@Override
public String toString(){
return this.name + "\t" + this.description;
}
}
如果我取消注释最后一个代码块 (Parameter.java) 中的两个 @XmlElement 行,则解组工作正常。如果不包括这两行,则 Parameter 对象中的两个字段都为空。在 XmlType 中使用 propOrder 时是否有另一种方法来声明命名空间?还是我做错了什么?