java – 使用JAXB处理丢失的节点
发布时间:2020-05-25 10:59:30 所属栏目:Java 来源:互联网
导读:我目前正在使用JAXB来解析xml文件.我通过xsd文件生成了所需的类.但是,我收到的xml文件不包含生成的类中声明的所有节点.以下是我的xml文件结构的示例: rootfirstChild12/12/2012/firstChild secondChildfirstGrandChildId /name characteristicsDescripti
|
我目前正在使用JAXB来解析xml文件.我通过xsd文件生成了所需的类.但是,我收到的xml文件不包含生成的类中声明的所有节点.以下是我的xml文件结构的示例: <root> <firstChild>12/12/2012</firstChild> <secondChild> <firstGrandChild> <Id> </name> <characteristics>Description</characteristics> <code>12345</code> </Id> </firstGrandChild> </secondChild> </root> 我面临以下两种情况: >节点< name>存在于生成的类中但不存在于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中/输出 <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<root>
<foo></foo>
</root> (编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
