我目前正在使用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>
Run Code Online (Sandbox Code Playgroud)
我面临以下两种情况:
<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;
}
}
Run Code Online (Sandbox Code Playgroud)
更新
JAXB 还将空节点视为具有empty 值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;
}
}
Run Code Online (Sandbox Code Playgroud)
演示
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);
}
}
Run Code Online (Sandbox Code Playgroud)
输入.xml/输出
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<root>
<foo></foo>
</root>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8658 次 |
| 最近记录: |