本文介绍了通过 XSTREAM 在 XML 中不需要的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 XStream 的新手

I am new to XStream

我有以下 DTO

@XStreamAlias("outline")
public class OutlineItem implements java.io.Serializable {

    private static final long serialVersionUID = -2321669186524783800L;

    @XStreamAlias("text")
    @XStreamAsAttribute
    private String text;

    @XStreamAlias("removeMe")
    private List<OutlineItem> childItems;
}

一旦我这样做

XStream stream = new XStream();
stream.processAnnotations(OutlineItem.class);
stream.toXML(outlineItem);

我把它作为我的输出文本

i get this as my output text

<outline text="Test">
  <removeMe>
    <outline text="Test Section1">
      <removeMe>
        <outline text="Sub Section1 1">
          <removeMe/>
        </outline>
        <outline text="Sub Section1 2">
          <removeMe/>
        </outline>
      </removeMe>
    </outline>
    <outline text="Test Section 2">
      <removeMe>
        <outline text="Test Section2 1">
          <removeMe/>
        </outline>
      </removeMe>
    </outline>
  </removeMe>
</outline>

而我希望输出是:

<outline text="Test">
    <outline text="Test Section1">
        <outline text="Sub Section1 1">
        </outline>
        <outline text="Sub Section1 2">
        </outline>
    </outline>
    <outline text="Test Section 2">
        <outline text="Test Section2 1">
        </outline>
    </outline>
</outline>

任何帮助将不胜感激!不确定是否需要某种 XSLT...

Any help will be greatly appreciated! Not sure if some kind of XSLT is required...

  • 沙阿

推荐答案

注意:我是EclipseLink JAXB (MOXy) 领导,也是 JAXB 的成员 (JSR-222) 专家组.

Note: I'm the EclipseLink JAXB (MOXy) lead, and a member of the JAXB (JSR-222) expert group.

我相信答案是:

@XStreamImplicit(itemFieldName="outline")
private List<OutlineItem> childItems;

您是否考虑过使用 JAXB 实现(MetroMOXy, JaxMe, ...) 代替?

Have you considered using a JAXB implementation (Metro, MOXy, JaxMe, ...) instead?

大纲项目

import javax.xml.bind.annotation.*;

@XmlRootElement(name="outline")
@XmlAccessorType(XmlAccessType.FIELD)
public class OutlineItem implements java.io.Serializable {

    private static final long serialVersionUID = -2321669186524783800L;

    @XmlAttribute
    private String text;

    @XmlElement("outline")
    private List<OutlineItem> childItems;

}

演示

import javax.xml.bind.*;

public class Demo {

    public static void main(String[] args) throws JAXBException {

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

        Marshaller marshaller = jaxbContext.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(outlineItem, System.out);

    }

}

这篇关于通过 XSTREAM 在 XML 中不需要的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 08:45