Java 用JAXB处理丢失的节点
我目前正在使用JAXB解析xml文件。我通过xsd文件生成了所需的类。但是,我收到的xml文件并不包含生成的类中声明的所有节点。以下是我的xml文件的结构示例:Java 用JAXB处理丢失的节点,java,xml,jaxb,Java,Xml,Jaxb,我目前正在使用JAXB解析xml文件。我通过xsd文件生成了所需的类。但是,我收到的xml文件并不包含生成的类中声明的所有节点。以下是我的xml文件的结构示例: <root> <firstChild>12/12/2012</firstChild> <secondChild> <firstGrandChild> <Id> </name> <characteristics>Description
<root>
<firstChild>12/12/2012</firstChild>
<secondChild>
<firstGrandChild>
<Id>
</name>
<characteristics>Description</characteristics>
<code>12345</code>
</Id>
</firstGrandChild>
</secondChild>
</root>
我面临以下两种情况:
存在于生成的类中,但不存在于XML文件中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/Output
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<root>
<foo></foo>
</root>
xsi:nil是你的朋友!请在此阅读更多内容,谢谢您的回答!据我所知,这是为了将节点的值设置为“”而不是null。我面临的问题是,对于JAXB,xml文件中的空节点和不存在的节点以相同的方式处理。因此,我不知道我是否在文件中收到了节点,它的值为空。下面的示例将有助于xsi:nil
:我需要为BigInteger数据类型和集合处理相同的问题,但对于BigInteger,布尔标志始终为false