【问题标题】:How work Jaxb to Unmarshal by Declared Type in Java?Jaxb 如何通过 Java 中的声明类型解组?
【发布时间】:2017-03-17 07:32:43
【问题描述】:

我尝试在 JAVA 中使用 JAXB 解组一个简单的 xml 文档:

<?xml version="1.0" encoding="UTF-8"?>
  <root>
    <fruit>banana</fruit>
    <fruit>apple</fruit>
    <vegetable>tomatoe</vegetable>
    <vegetable>potatoe</vegetable>
    <fruit>pineaple</fruit>
    <vegetable>cabbage</vegetable>
    <vegetable>carrot</vegetable>
    <fruit>strawberry</fruit>
  </root>

看不懂是怎么工作的

unmarshal <T> JAXBElement<T> unmarshal(Node node,Class<T> declaredType) throws JAXBException

因为对于我的问题,我必须用 JAXB 和解组来代表所有“根”子级。 我需要将此 xml 解组为 java 对象。

感谢之前花时间解决我的问题。

【问题讨论】:

    标签: java xml jaxb unmarshalling


    【解决方案1】:

    仅用于从根元素解组:

    JAXBContext jaxbContext = JAXBContext.newInstance(ObjectFactory.class);
    Unmarshaller unmarhsaller = jaxbContext.createUnmarshaller();
    Root root = (Root) unmarhsaller.unmarshal(new File("file.xml"));
    
    //getting a list of fruit nodes (suppose you have created XML document object model)
    List<Fruit> fruit = root.getFruit();
    // do your stuff here
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-02-20
      • 2022-01-10
      • 1970-01-01
      • 2012-08-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多