【问题标题】:Unwanted elements in XML via XSTREAM通过 XSTREAM 在 XML 中不需要的元素
【发布时间】:2011-10-13 21:03:19
【问题描述】:

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

我把它作为我的输出文本

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

  • 沙阿

【问题讨论】:

    标签: java xml xslt xstream


    【解决方案1】:

    注意:我是 EclipseLink JAXB (MOXy) 负责人,也是 JAXB (JSR-222) 专家组的成员。


    我相信答案是:

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

    您是否考虑过使用 JAXB 实现(MetroMOXyJaxMe、...)?

    大纲项

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

    【讨论】:

    • 感谢您的解决方案。它工作得很好。我还要看看 JAXB。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-13
    • 2011-04-13
    • 1970-01-01
    • 2013-08-19
    相关资源
    最近更新 更多