使用 JAXB 解组 xml 字符串但得到空字符串

Posted

技术标签:

【中文标题】使用 JAXB 解组 xml 字符串但得到空字符串【英文标题】:Using JAXB to unmarshal a xml string but get empty one 【发布时间】:2016-02-05 22:44:33 【问题描述】:

问题解决了

将XmlElementRef注解更改为@XmlElementRef(name = "Option", type = Option.class, required = false) 并将@XmlRootElement(name = "Option") 添加到Option.class


更新:

按照 laune 的建议,我添加了两个类(Options 和 Option),并修改了 GuiMOProperties 类,如下所示

@XmlAccessorType(XmlAccessType.FIELD)
public class GuiMOProperties

    @XmlElement(name="Grouping")
    private boolean                 grouping;
    @XmlElement(name="Type")
    private String                  type;
    @XmlElement(name="Regex")
    private String                  regex;
    @XmlElement(name="DisplayName")
    private String                  displayName;
    @XmlElement(name="Options")
    private Options                 options;
    @XmlElement(name="Mask")
    private String                  mask;
    @XmlElement(name="DefaultValue")
    private String                  defaultValue;

但是当我必须新建一个 JAXBContext 实例时出现了一些异常,如下所示:

JAXBContext jaxbContext = JAXBContext.newInstance(GuiMOProperties.class);


java.lang.IllegalArgumentException: can't parse argument number: ''0''
at java.text.MessageFormat.makeFormat(MessageFormat.java:1429)
at java.text.MessageFormat.applyPattern(MessageFormat.java:479)
at java.text.MessageFormat.<init>(MessageFormat.java:362)
at java.text.MessageFormat.format(MessageFormat.java:840)
at com.sun.xml.internal.bind.v2.model.impl.Messages.format(Messages.java:117)
at com.sun.xml.internal.bind.v2.model.impl.ReferencePropertyInfoImpl.calcTypes(ReferencePropertyInfoImpl.java:171)
at com.sun.xml.internal.bind.v2.model.impl.ReferencePropertyInfoImpl.link(ReferencePropertyInfoImpl.java:372)
at com.sun.xml.internal.bind.v2.model.impl.ClassInfoImpl.link(ClassInfoImpl.java:1257)
at com.sun.xml.internal.bind.v2.model.impl.RuntimeClassInfoImpl.link(RuntimeClassInfoImpl.java:182)
at com.sun.xml.internal.bind.v2.model.impl.ModelBuilder.link(ModelBuilder.java:439)
at com.sun.xml.internal.bind.v2.model.impl.RuntimeModelBuilder.link(RuntimeModelBuilder.java:118)
at com.sun.xml.internal.bind.v2.runtime.JAXBContextImpl.getTypeInfoSet(JAXBContextImpl.java:443)
at com.sun.xml.internal.bind.v2.runtime.JAXBContextImpl.<init>(JAXBContextImpl.java:277)
at com.sun.xml.internal.bind.v2.runtime.JAXBContextImpl.<init>(JAXBContextImpl.java:124)
at com.sun.xml.internal.bind.v2.runtime.JAXBContextImpl$JAXBContextBuilder.build(JAXBContextImpl.java:1123)
at com.sun.xml.internal.bind.v2.ContextFactory.createContext(ContextFactory.java:147)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at javax.xml.bind.ContextFinder.newInstance(ContextFinder.java:247)
at javax.xml.bind.ContextFinder.newInstance(ContextFinder.java:234)
at javax.xml.bind.ContextFinder.find(ContextFinder.java:462)
at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:641)
at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:584)
at devicemanage.utility.Tree2xml.omElementToGuiMOPropertiesList(Tree2xml.java:332)
at devicemanage.service.appdeploy.DeviceMgtServiceImpl.getMOProperties(DeviceMgtServiceImpl.java:250)
at devicemanage.service.appdeploy.DeviceMgtServiceImpl.access$0(DeviceMgtServiceImpl.java:238)
at devicemanage.service.appdeploy.DeviceMgtServiceImpl$1.load(DeviceMgtServiceImpl.java:233)
at devicemanage.service.appdeploy.DeviceMgtServiceImpl$1.load(DeviceMgtServiceImpl.java:1)
at com.google.common.cache.LocalCache$LoadingValueReference.loadFuture(LocalCache.java:3527)
at com.google.common.cache.LocalCache$Segment.loadSync(LocalCache.java:2319)
at com.google.common.cache.LocalCache$Segment.lockedGetOrLoad(LocalCache.java:2282)
at com.google.common.cache.LocalCache$Segment.get(LocalCache.java:2197)
at com.google.common.cache.LocalCache.get(LocalCache.java:3937)
at com.google.common.cache.LocalCache.getOrLoad(LocalCache.java:3941)
at com.google.common.cache.LocalCache$LocalLoadingCache.get(LocalCache.java:4824)
at devicemanage.service.appdeploy.DeviceMgtServiceImpl.findMOPropertiesByDeviceType(DeviceMgtServiceImpl.java:208)
at devicemanage.service.appdeploy.DeviceMgtServiceImpl$$FastClassBySpringCGLIB$$1a89f063.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:717)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:98)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:266)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:95)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:653)
at devicemanage.service.appdeploy.DeviceMgtServiceImpl$$EnhancerBySpringCGLIB$$97274215.findMOPropertiesByDeviceType(<generated>)
at TestDeviceMgtService.testFindMOPropertiesByDeviceType(TestDeviceMgtService.java:38)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:72)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:81)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:72)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:216)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:82)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:60)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:67)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:162)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Caused by: java.lang.NumberFormatException: For input string: "''0''"
    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
    at java.lang.Integer.parseInt(Integer.java:569)
    at java.lang.Integer.parseInt(Integer.java:615)
    at java.text.MessageFormat.makeFormat(MessageFormat.java:1427)
    ... 78 more

我有一个定义如下用于 JAXB 解析的类:

@XmlAccessorType(XmlAccessType.FIELD)
public class GuiMOProperties

    @XmlElement(name="Grouping")
    private boolean                 grouping;
    @XmlElement(name="Type")
    private String                  type;
    @XmlElement(name="Regex")
    private String                  regex;
    @XmlElement(name="DisplayName")
    private String                  displayName;
    @XmlElement(name="Options")
    @XmlJavaTypeAdapter(OptionsAdapter.class)
    private GuiMOOption                 options;
    @XmlElement(name="Mask")
    private String                  mask;
    @XmlElement(name="DefaultValue")
    private String                  defaultValue;

我必须解析的xml字符串如下:

            <VolumeUpKey>
                <Type/>
                <Regex/>
                <DisplayName/>
                <Options>testOptions</Options>
                <Mask/>
                <DefaultValue/>
            </VolumeUpKey>
            <SSID>
                <Type/>
                <Regex/>
                <DisplayName/>
                <Options>
                    <Option name="1" value="1"></Option>
                    <Option name="2" value="2"></Option>
                    <Option name="3" value="3"></Option>
                    <Option name="4" value="4"></Option>
                </Options>
                <Mask/>
                <DefaultValue/>
            </SSID>

在我的 OptionsAdapter.class 的 unmarshal 方法中,第一个 Options 元素工作正常,有一个字符串“testOptions”输入。但是,第二个 Options 元素没有。输入参数将是 \n\t\t\t\t,但不是字符串 &lt;Option name="1" value="1"&gt;&lt;/Option&gt;&lt;Option name="2" value="2"&gt;&lt;/Option&gt;&lt;Option name="3" value="3"&gt;&lt;/Option&gt;&lt;Option name="4" value="4"&gt;&lt;/Option&gt;

OptionsAdapter.class 如下

public class OptionsAdapter extends XmlAdapter<String, GuiMOOption>

    @Override
    public GuiMOOption unmarshal(String v) throws Exception
    
        try
        
            System.out.println("unmarshal string : " + v);
         catch (Exception e)
        
            // TODO: handle exception
        

        return null;
    

    @Override
    public String marshal(GuiMOOption v) throws Exception
    
        // TODO Auto-generated method stub
        return null;
    

感谢任何帮助。

【问题讨论】:

【参考方案1】:

混合内容不是很简单,尽管 JAXB 可以在没有适配器的情况下处理它。

您可以将选项字段的类型定义为 Options(而不是 GuiMOOption):

@XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "选项", propOrder = “内容” ) 公共类选项 @XmlElementRef(name = "field", type = JAXBElement.class, required = false) @XmlMixed 受保护的列表内容; 公共列表 getContent() 如果(内容==空) 内容 = 新的 ArrayList(); 返回 this.content;

List 将包含 JAXBElement&lt;Option&gt; 和 String 类型的元素,其中 Option 是一个类

@XmlAccessorType(XmlAccessType.FIELD) 公共类选项 @XmlAttribute 受保护的字符串名称; @XmlAttribute 受保护的字符串值; //...

您必须迭代 List 以了解您拥有的是第一个 XML 表单还是第二个 XML 表单。在第一种情况下,只有一个字符串。在第二种情况下,包装的 Option 对象之间可能存在空白字符串。

【讨论】:

您好,劳恩,感谢您的回答。你的意思是我要添加两个类Options和Option,然后去掉@XmlJavaTypeAdapter注解。就让 GuiMOProperties 的 options 字段变成 XMLElement(name="Options")? 就是这样。 - 我使用了新名称,不确定您的 GuiMOOption 类型是如何定义的。 我还没有定义 GuiMOOption,但是在添加选项和选项后,我更新的帖子出现了一些异常。谢谢 一切都从头开始清理和重建了吗? 嗨,劳恩,问题已解决。感谢您的回答。我已将 XmlElementRef 注释修改为 @XmlElementRef(name = "Option", type = Option.class, required = false) 并将 @XmlRootElement(name = "Option") 添加到 Option.class,这样就可以了。

以上是关于使用 JAXB 解组 xml 字符串但得到空字符串的主要内容,如果未能解决你的问题,请参考以下文章

使用 Xpath 表达式和 jaxb 解组 XML

JAXB:如何在解组 XML 文档期间忽略命名空间?

使用 DTD 文件导致的 JAXB 解组 XML 时出错

如何跳过字段并仅使用JAXB解组该字段的特定成员?

使用 JAXB 解组多次出现的 XML 元素

Java/JAXB:根据属性将 Xml 解组为特定子类