用于解组和编组的 XML 注释 (JAXB) 建议 [英] XML annotations (JAXB) suggestions for unmarshalling and marshalling

查看:58
本文介绍了用于解组和编组的 XML 注释 (JAXB) 建议的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个示例 XML,如下所示:

I have a sample XML as shown below:

<?xml version="1.0" encoding="UTF-8"?>
<Education>
    <School name="ABC" location="Mangalore">
        <Student gender="M" housepincode="575020">
            <FirstName>VJ</FirstName>
            <LastName>K</LastName>
        </Student>
        <Student gender="M" housepincode="575002">
            <FirstName>S</FirstName>
            <LastName>K</LastName>
        </Student>
    </School>
</Education>

这已在 JAXB 的帮助下使用以下方法解组.我有教育、学校和学生课程.

This has been unmarshalled with the help of JAXB using the following approach. I have classes for Education,School and Student.

教育.java

import lombok.Data;
@Data
@XmlRootElement(name = "Education")
public class Education {    
    public School School;
}

学校.java

import lombok.Data;
@Data
@XmlAccessorType(XmlAccessType.FIELD)
public class School {   
    @XmlAttribute
    private String name;    
    @XmlAttribute
    private String location;    
    @XmlElement(name ="Student")
    private List<Student> Student;
}

Student.java

Student.java

@Data
@XmlAccessorType(XmlAccessType.FIELD)
public class Student {      
    @XmlAttribute
    private String gender;  
    @XmlAttribute
    private String housepincode;    
    @XmlElement(name = "FirstName")
    private String FirstName;
    @XmlElement(name = "LastName")
    private String LastName;
}

我对收到的输出有些担忧.首先,有一些警告.我相信这是因为我错过了一些应该存在的注释.请问这里有什么建议或指导吗?

I have some concerns over the output I receive. First of all there are some warnings. I believe it is because i have missed some annotations which should be present. Any suggestions or guidance here please?

WARNING: An illegal reflective access operation has occurred
WARNING: Illegal reflective access by com.sun.xml.bind.v2.runtime.reflect.opt.Injector (file:/C:/Users/R.Premsagar/.m2/repository/org/glassfish/jaxb/jaxb-runtime/2.3.0-b170127.1453/jaxb-runtime-2.3.0-b170127.1453.jar) to method java.lang.ClassLoader.defineClass(java.lang.String,byte[],int,int)
WARNING: Please consider reporting this to the maintainers of com.sun.xml.bind.v2.runtime.reflect.opt.Injector
WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations
WARNING: All illegal access operations will be denied in a future release

Education(School=School(name=ABC, location=Mangalore, Student=[Student(gender=M, housepincode=575020, FirstName=VJ, LastName=K), Student(gender=M, housepincode=575002, FirstName=S, LastName=K)]))

此外,输出的层次结构对我来说似乎不正确,例如:School = School 标签?我想将此输出打印到单独的 XML 以验证结果.但是脚本失败了

Also, the heirarchy of output does not seem correct to me, Eg: School = School tag? I want to print this output to a separate XML to verify the result. However the script fails

主程序:

List<Education> Entries = new ArrayList<Education>();
        try {
            File xmlFile = new File("Withattributes.xml");
            JAXBContext jaxbContext;
            jaxbContext = JAXBContext.newInstance(Education.class);                          
            Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();        
            Education entries = (Education) jaxbUnmarshaller.unmarshal(xmlFile);    
            Entries.add(entries); //storing objects in a list for later use
            
            
            //--------------------------------------------------------------
            JAXBContext jaxbContext_w = JAXBContext.newInstance(Education.class);           
            Marshaller jaxbMarshaller = jaxbContext_w.createMarshaller();
            jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
            jaxbMarshaller.marshal(jaxbContext_w, System.out);
}
        catch (JAXBException e) 
        {
            e.printStackTrace();
        } catch (FactoryConfigurationError e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
}

我收到以下错误消息:

Neither the class com.sun.xml.bind.v2.runtime.JAXBContextImpl nor one of the associated superclasses is known to this context.
at com.sun.xml.bind.v2.runtime.JAXBContextImpl.getBeanInfo(JAXBContextImpl.java:593)
    at com.sun.xml.bind.v2.runtime.XMLSerializer.childAsRoot(XMLSerializer.java:482)
    at com.sun.xml.bind.v2.runtime.MarshallerImpl.write(MarshallerImpl.java:328)
    at com.sun.xml.bind.v2.runtime.MarshallerImpl.marshal(MarshallerImpl.java:256)
    at javax.xml.bind.helpers.AbstractMarshallerImpl.marshal(AbstractMarshallerImpl.java:110)
    at JaxbExample.main(JaxbExample.java:39)

请让我知道这里可以做什么..

Please let me know what could be done here..

更新:

如果 XML 更新为具有如下结构:

If the XML is updated to have a structure as below:

<?xml version="1.0" encoding="UTF-8"?>
<Education>
    <School name="ABC" location="Mangalore">
        <Student gender="M" housepincode="575020">
            <FirstName>VJ</FirstName>
            <LastName>K</LastName>
            <Hobbies>
                  <Hobby time = "M">Novels</Hobby>
                  <Hobby time = "A">Gaming</Hobby>
            </Hobbies>
        </Student>
    </School>
</Education>

现在 Student.java 的类将更改为

Now the class of Student.java would change to

@Data
@XmlAccessorType(XmlAccessType.FIELD)
public class Student {      
    @XmlAttribute
    private String gender;  
    @XmlAttribute
    private String housepincode;    
    @XmlElement(name = "FirstName")
    private String FirstName;
    @XmlElement(name = "LastName")
    private String LastName;
    @XmlElementWrapper(name ="Hobbies")
    @XmlElement(name="Hobby")
    private List<Hobby> Hobbies;
}

和 Hobby.java

and the Hobby.java

@Data
@XmlAccessorType(XmlAccessType.FIELD)
public class Hobby{
    
    @XmlAttribute(name="Time")
    private String Time;
    
    @XmlElement
    private String Hobby;

}

通过这个修改,我没有得到 Hobby 标签的值.我得到的爱好和价值观列表如下:

With this modification I do not get the value of the Hobby tag. I get the list of Hobbies and values something like this:

            Hobbies>
                  <Hobby time = "M"/>
                  <Hobby time = "A"/>
            </Hobbies>

你能在这里纠正我吗?

推荐答案

第一期:我不是 JAXB 方面的专家,所以我不知道什么可能导致此处指定的警告,但我尝试遵循代码,它似乎对我来说工作正常,没有任何警告.如果你想获得更多的理解,那么最好的办法就是搜索它并阅读文档以获取更多信息.但我的猜测是由于您的第二个问题.

First issue: I am no expert on JAXB so I do not have much idea on what could cause the warnings specified here but I tried following the code and it seems to work fine for me without any warnings. If you want to get more understanding then the best thing to do is search about it and read the doc to get more information. But my guess is that it's happening due to your second issue.

此外,我使用的是 Moxy,它是 Eclipse-link 开发的 JAXB 的扩展.与简单的 JAXB

Also, I am using Moxy which is an extension of JAXB developed by Eclipse-link. It has many additional benefits compared to simple JAXB

第二期:明显错误在这一行:

Second issue: obvious error is in this line:

jaxbMarshaller.marshal(jaxbContext_w, System.out);

你为什么提供 jaxbContext_w 作为它的输入.它应该是未编组的值.在您的情况下,它是 entries.

why are you providing jaxbContext_w as an input to it. It should be the unmarshalled values. In your case, it is entries.

完整代码如下:教育:

@Data
@XmlRootElement(name = "Education")
@XmlAccessorType(XmlAccessType.FIELD)
public class Education {
    public School School;
}

学校:

@Data
@XmlAccessorType(XmlAccessType.FIELD)
public class School {
    @XmlAttribute
    private String name;

    @XmlAttribute
    private String location;

    @XmlElement
    private List<Student> Student;
}

学生:

@Data
@XmlAccessorType(XmlAccessType.FIELD)
public class Student {
    @XmlAttribute
    private String gender;

    @XmlAttribute
    private String housepincode;

    @XmlElement
    private String FirstName;

    @XmlElement
    private String LastName;
}

主要内容:


public class Main {
    public static void main(String[] args) throws JAXBException, XMLStreamException {
        final InputStream inputStream = Main.class.getClassLoader().getResourceAsStream("students.xml");
        final XMLStreamReader xmlStreamReader = XMLInputFactory.newInstance().createXMLStreamReader(inputStream);
        final Unmarshaller unmarshaller = JAXBContext.newInstance(Education.class).createUnmarshaller();
        final Education education = unmarshaller.unmarshal(xmlStreamReader, Education.class).getValue();
        System.out.println(education.toString());

        Marshaller marshaller = JAXBContext.newInstance(Education.class).createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        marshaller.marshal(education, System.out);
    }
}

输出(没有任何错误或警告):

Output (Without any error or warnings):


Education(School=School(name=ABC, location=Mangalore, Student=[Student(gender=M, housepincode=575020, FirstName=VJ, LastName=K), Student(gender=M, housepincode=575002, FirstName=S, LastName=K)]))
<Education>
   <School name="ABC" location="Mangalore">
      <Student gender="M" housepincode="575020">
         <FirstName>VJ</FirstName>
         <LastName>K</LastName>
      </Student>
      <Student gender="M" housepincode="575002">
         <FirstName>S</FirstName>
         <LastName>K</LastName>
      </Student>
   </School>
</Education>

这篇关于用于解组和编组的 XML 注释 (JAXB) 建议的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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