【问题标题】:Read the XML tree(Root, parents and Children) using JAXB2 in JAVA and create marshalling and unmarshalling在 JAVA 中使用 JAXB2 读取 XML 树(根、父级和子级)并创建编组和解组
【发布时间】:2014-12-03 16:14:56
【问题描述】:

我需要在 Java 中创建一个类似的树(根、父和子)结构。抱歉,我是新来的,无法附上图片。我发现了一些与此相关的问题,但我还没有找到令人信服且解释清楚的回答。应用业务包括食品超级品类(主菜、甜品等)。这些类别中的每一个都可以有父项或子项等。

我需要使用 JAXB2 在 Java 中编组和解组 xml 树结构

我的 xml 看起来像

<Hierarchy name="" desc="" title="" tablename=""> 
    <Columns> 
        <column name="" desc="" group="" id=""/> 
     </Columns> 
     <Nodes> 
         <Node name=" " desc="" id=""> 
             <Node name="" desc="" id="" /> 
         </Node> <Node name=" " desc="" id="" /> 
    </Nodes> 
    <Rules> 
        <Rule name="" node="" measure="" product="" dataset="" datatype="" /> 
    </Rules>
</Hierarchy>

【问题讨论】:

  • 我的 xml 看起来像这样
    ''
    ' '












    '
  • 到目前为止你做了什么?请在您的问题中发布您的 xml。
  • 对不起,我的格式不起作用.. 我的 xml 看起来像
  • 为什么不工作?错误是什么?
  • 我基本上需要在java中使用JAXB2读取xml树并且需要对结果进行编组和解组。你能建议吗

标签: java tree marshalling unmarshalling jaxb2


【解决方案1】:

基本上,您需要先将 XML 转换为 java 对象,然后再对结果进行编组和解组。 如果这是您的 XML 文件:

<Hierarchy name="" desc="" title="" tablename="">
    <Columns> 
        <column name="" desc="" group="" id=""/>
    </Columns>
    <Nodes>
        <Node name=" " desc="" id="">
            <Node name="" desc="" id="" />
        </Node>
        <Node name=" " desc="" id="" /> 
    </Nodes>
    <Rules>
        <Rule name="" node="" measure="" product="" dataset="" datatype="" />
    </Rules>
</Hierarchy>

你可以这样做:

package org.arpit.javapostsforlearning.jaxb;

import java.io.File;
import java.util.ArrayList;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;

public class JAXBXMLToJava {
    public static void main(String[] args) {
          try {
                // create JAXB context and initializing Marshaller
                // you need to make the class of food before
                JAXBContext jaxbContext = JAXBContext.newInstance(Food.class);

                Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();

                // specify the location and name of xml file to be read
                File XMLfile = new File('MyXml.xml');

                // this will create Java object - Food from the XML file
                Food desserts  = (Food) jaxbUnmarshaller.unmarshal(XMLfile);

                System.out.println('Food Name: '+ desserts.getName());

          } catch (JAXBException e) {
                e.printStackTrace();
          }
     }
} 

查看Here 获取完整示例。

【讨论】:

  • 谢谢尼玛,这很有帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-07
  • 2018-05-13
  • 1970-01-01
  • 2023-04-06
  • 1970-01-01
相关资源
最近更新 更多