我目前正在使用 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 文件中 - 节点没有值
在这两种情况下,该值都设置为空。我希望能够区分节点何时不在 XML 文件中以及何时存在但具有空值。尽管我进行了搜索,但我没有找到这样做的方法。任何帮助都非常受欢迎
非常感谢您的宝贵时间和帮助
问候
最佳答案
A 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;
}
}
更新
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>
关于java - 使用 JAXB 处理丢失的节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15839276/