Unwanted elements in XML via XSTREAM

夙愿已清 提交于 2019-12-08 13:50:23

问题


I am new to XStream

I have following 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;
}

once i do

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>

whereas i want the output to be:

<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>

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

  • Shah

回答1:


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


I believe the answer is:

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

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

  • Modern alternative to Java XStream library?
  • http://bdoughan.blogspot.com/2010/10/how-does-jaxb-compare-to-xstream.html

OutlineItem

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;

}

Demo

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);

    }

}


来源:https://stackoverflow.com/questions/6838312/unwanted-elements-in-xml-via-xstream

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!