JAXB获取原始xml,同时解组元素列表

时间:2015-02-03 11:00:36

标签: java xml jaxb

我有一个xml输入,如下所示

<Confirmations>
 <SystemConf>
     <SysCnf>
        <MessageId>1</MessageId>
     </SysCnf>
     <SysCnf>
        <MessageId>2</MessageId>
     </SysCnf>
  </SystemConf>
</Confirmations>

这些是我的课程

@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = "Confirmations")

public class Confirmations
{

@XmlElementWrapper(name = "SystemConf")
@XmlElement(name = "SysCnf")
private List<SystemConfirmation> systemConfirmations = null;


public List<SystemConfirmation> getSystemConfirmations()
{
    return systemConfirmations;
}

public void setSystemConfirmations(List<SystemConfirmation> systemConfirmations)
{
    this.systemConfirmations = systemConfirmations;
}

}


@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "SysCnf")
public class SystemConfirmation
{
@XmlElement(name = "MessageId")
private String messageId;

public void setMessageId(String messageId)
{
     this.messageId = messageId;
}

public String getMessageId()
{
    return messageId;
}


@XmlAnyElement(value = SysConfXmlStringHandler.class)
private String xml;


public String getXml()
{
    return xml;
}
}


public class SysConfXmlStringHandler implements DomHandler<String, StreamResult>
{
private static final String SYSCONF_START_TAG = "<SycCnf>";

private static final String SYSCONF_END_TAG = "</SysCnf>";
private StringWriter xmlWriter = new StringWriter();

@Override
public StreamResult createUnmarshaller(ValidationEventHandler errorHandler)
{
    return new StreamResult(xmlWriter);
}

@Override
public String getElement(StreamResult rt)
{
    String xml = rt.getWriter().toString();
    System.out.println(xml);
    int beginIndex = xml.indexOf(SYSCONF_START_TAG) + SYSCONF_START_TAG.length();
    int endIndex = xml.indexOf(SYSCONF_END_TAG);
    return xml.substring(beginIndex, endIndex);
}

@Override
public Source marshal(String n, ValidationEventHandler errorHandler)
{
    try
    {
        String xml = SYSCONF_START_TAG + n.trim() + SYSCONF_END_TAG;
        StringReader xmlReader = new StringReader(xml);
        return new StreamSource(xmlReader);
    }
    catch (Exception e)
    {
        throw new RuntimeException(e);
    }
}
}

问题 在SystemConfirmation类的xml字段中,我想要特定的SystemConfirmation块xmml元素的整个xml,它位于

之下
<SysCnf>
    <MessageId>1</MessageId>
</SysCnf>

有谁知道如何实现这一目标?我尝试了上面的代码但是我只在xml中获取MessageId块,如果我在SystemConfirmation中添加多个字段,那么我只获得第一个。

0 个答案:

没有答案