使用JAXB处理丢失的节点 [英] Handling missing nodes with JAXB

查看:160
本文介绍了使用JAXB处理丢失的节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用JAXB来解析xml文件。我通过xsd文件生成了所需的类。但是,我收到的xml文件不包含生成的类中声明的所有节点。以下是我的xml文件结构的示例:

I am currently using JAXB to parse xml files. I generated the classes needed through an xsd file. However, the xml files I receive do not contain all the nodes declared in the generated classes. The following is an example of my xml file's structure:

<root>
<firstChild>12/12/2012</firstChild> 
<secondChild>
<firstGrandChild>
<Id>
  </name>
  <characteristics>Description</characteristics> 
  <code>12345</code>
</Id>
</firstGrandChild>
</secondChild>
</root>

我面临以下两种情况:


  1. 节点< name> 存在于生成的类中但不存在于XML文件中

  2. 节点没有值

  1. The node <name> is present in the generated classes but not in the XML files
  2. The node has no value

在这两种情况下,该值都设置为null。我希望能够区分XML文件中何时缺少节点以及何时存在但具有空值的节点。尽管我的搜索,我还没有找到办法。任何帮助都非常欢迎

In both cases, the value is set to null. I would like to be able to differentiate when the node is absent from the XML file and when it's present but has a null value. Despite my searches, I didn't figure out a way to do so. Any help is more than welcome

非常感谢您提前花时间和帮助

Thank you so much in advance for your time and help

问候

推荐答案

A JAXB(JSR-222) 实现不会为缺少的节点调用set方法。你可以在你的set方法中输入逻辑来跟踪它是否被调用。

A JAXB (JSR-222) implementation won't call the set method for absent nodes. You could put logic in your set method to track whether or not it has been called.

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

JAXB will also treat empty nodes as having a value of 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;
    }

}

演示

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>

这篇关于使用JAXB处理丢失的节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆