使用JAXB处理丢失的节点
我目前正在使用JAXB来解析xml文件。 我通过xsd文件生成了所需的类。 但是,我收到的xml文件不包含生成的类中声明的所有节点。 以下是我的xml文件结构的示例:
12/12/2012 Description 12345
我面临以下两种情况:
- 节点
存在于生成的类中,但不存在于XML文件中
- 该节点没有任何价值
在这两种情况下,该值都设置为null。 我希望能够区分XML文件中何时缺少节点以及何时存在但具有空值。 尽管我的搜索,我还没有找到办法。 任何帮助都非常受欢迎
非常感谢您的时间和帮助
问候
JAXB(JSR-222)实现不会为缺少的节点调用set方法。 您可以在set方法中放置逻辑以跟踪它是否已被调用。
public class Foo { private String bar; private boolean barSet = false; public String getBar() { return bar; } public void setBar(String bar) { this.bar = bar; this.barSet = true; } }
UPDATE
JAXB还将空节点视为具有空String
的值。
Java模型
import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement public class Root { private String foo; private String bar; public String getFoo() { return foo; } public void setFoo(String foo) { this.foo = foo; } public String getBar() { return bar; } public void setBar(String bar) { this.bar = bar; } }
演示
import java.io.File; import javax.xml.bind.*; public class Demo { public static void main(String[] args) throws Exception { JAXBContext jc = JAXBContext.newInstance(Root.class); Unmarshaller unmarshaller = jc.createUnmarshaller(); File xml = new File("src/forum15839276/input.xml"); Root root = (Root) unmarshaller.unmarshal(xml); Marshaller marshaller = jc.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); marshaller.marshal(root, System.out); } }
input.xml中/输出