java - 通过 XSTREAM 处理 XML 中不需要的元素

标签 java xml xslt xstream

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

  • 沙阿

最佳答案

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

    }

}

关于java - 通过 XSTREAM 处理 XML 中不需要的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6838312/

相关文章:

android - 我的 Xml 设计不适用于所有 Android 设备?

c# - 加载特定 XML 节点值 C#

xml - 如何在 XML 架构元素中添加空格?

xml - 在浏览器中显示 UML

xslt - 在 Saxon 中处理无限递归 XSL

java - 使用注释处理生成单元测试

java - Java中如何通过内部类实例获取外部类实例

java - 这段代码中的变量 'x' 会存储在堆栈内存、堆内存还是两者中?

java - 如何在 Jasper Reports/JRXML 中进行复杂计算

xml - 将斜体 XML 标签转换为 WordML 标签