【问题标题】:facing issue with unmarshalling an old xml ,after class structure got changed在更改类结构后面临解组旧 xml 的问题
【发布时间】:2017-06-15 12:30:38
【问题描述】:

我正在努力解组结构与我当前的对象结构不同的旧 xml 文件。

以前的结构

@xmlRootElement("configData")
public class configData{  
 private string name; 
 private string age; 
 private customObject obj;
}

我当前的数据结构是

@xmlRootElement("configData")
public class configData{  
  List<SampleData> sampleDatas;;

}

public class SampleData{
  private string name; 
  private string age; 
  private customObject obj;

 }

如何使它与旧的 xml 文件一起工作。请帮忙。

谢谢

【问题讨论】:

  • 您可以将访问器方法委托给configData,并将列表标记为@XmlTransient...
  • 我是 JAXB 映射的新手。 @xmlTransient 在这种情况下会有什么帮助?你能详细说明一下吗

标签: java xml jaxb unmarshalling


【解决方案1】:

您的旧结构表明,XML 文件中只存在一组 SampleData
所以你应该尝试这样的事情:

@XmlRootElement
public class ConfigData
{
  // This will hide the list from JAXB
  @XmlTransient
  private final List<SampleData> sampleDatas = new ArrayList<>();

  private SampleData getFirstSample()
  {
    if(sampleDatas.isEmpty())
      sampleDatas.add(new SampleData());
    return sampleDatas.get(0);
  }

  // Façade methods to delegate functionality to the list's first item...
  // Only setters are required, if you just want to read in an old format.
  // However this would not be optional, if you want to save to the new format...
  public void setName(String name)
  {
    getFirstSample().setName(name);
  }

  public void seAge(String age)
  {
    getFirstSample().setAge(age);
  }

  public void setObj(CustomObject obj)
  {
    getFirstSample().setObj(obj);
  }
}

public class SampleData
{
  private String name; 
  private String age; 
  private CustomObject obj;
  // Accessor methods...
}

ConfigData 中的外观设置方法将它们的值存储到列表的第一项。

为了提供保存的可能性,您应该删除@XmlTransient,并为您要保存的字段提供public getter...

【讨论】:

  • 感谢您花时间解决我的问题。是的你是对的。旧的 XML 文件有一组示例数据。但是,我将如何获取第一个 sampleData 对象中的属性值,除非我也复制了 configData 类中的属性?我需要以新格式保存数据。
  • 我没有在我的第一个 SampleData 对象中获得属性值。对于旧的 XML 文件,它始终为 null。
  • 谢谢!!!它正在工作。我将@xmlElement 注释应用于configData 类中的所有设置器
猜你喜欢
  • 1970-01-01
  • 2020-12-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多