所以我有一个像
这样的课程@XmlAccessorType(value = XmlAccessType.FIELD)
public class Item {
@XmlAttribute
private String idA;
private String nameA;
@XmlAttribute
private String idB;
private String nameB;
@XmlAttribute
private String idC;
private String nameC;
public Item() {
}
public Item(String idA, String nameA, String idB, String nameB, String idC, String nameC) {
this.idA = idA;
this.nameA = nameA;
this.idB = idB;
this.nameB = nameB;
this.idC = idC;
this.nameC = nameC;
}
@Override
public String toString() {
return "Item [nameA = " + nameA + ", nameB = " + nameB + ", nameC = " + nameC + "]";
}
}
它的容器:
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Items {
private List<Item> items;
public Items() {
}
public Items(List<Item> items) {
this.items = items;
}
}
我正在使用这个监听器在每个项目之后写评论:
public class AddCommentsListener extends Marshaller.Listener {
private XMLStreamWriter xsw;
public AddCommentsListener(XMLStreamWriter xsw) {
this.xsw = xsw;
}
@Override
public void beforeMarshal(Object source) {
}
@Override
public void afterMarshal(Object source) {
if (source instanceof Item) {
try {
xsw.writeComment(source.toString());
} catch (XMLStreamException e) {
}
}
}
}
最后我的测试类是:
public class Test {
public static <T> void saveToXml(T entity, OutputStream stream) {
try {
JAXBContext jc = JAXBContext.newInstance(entity.getClass());
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.setListener(new AddCommentsListener(XMLOutputFactory.newFactory().createXMLStreamWriter(stream)));
marshaller.marshal(entity, stream);
} catch (JAXBException | XMLStreamException e) {
System.out.println(e);
}
}
public static void main(String[] args) throws FileNotFoundException {
List<Item> items = new ArrayList<>();
for (int i =0 ;i < 100; i++) {
String idA = String.format("idA %s", i);
String nameA = String.format("locationA %s", i);
String idB = String.format("idB %s", i);
String nameB = String.format("locationB %s", i);
String idC = String.format("idC %s", i);
String nameC = String.format("locationC %s", i);
items.add(new Item(idA, nameA, idB, nameB, idC, nameC));
}
Path path = Paths.get("out.txt");
saveToXml(new Items(items), new FileOutputStream(path.toFile()));
}
}
输出:
<items idA="idA 17" idB="idB 17" idC="idC 17">
<nameA>locationA 17</nameA>
<nameB>locationB 17</nameB>
<nameC>locationC 17<!--Item [nameA = locationA 17, nameB = locationB 17, nameC = locationC 17]--><!--Item [nameA = locationA 18, nameB = locationB 18, nameC = locationC 18]--><!--Item [nameA = locationA 19, nameB = locationB 19, nameC = locationC 19]--><!--Item [nameA = locationA 20, nameB = locationB 20, nameC = locationC 20]--><!--Item [nameA = locationA 21, nameB = locationB 21, nameC = locationC 21]--><!--Item [nameA = locationA 22, nameB = locationB 22, nameC = locationC 22]--></nameC>
</items>
但评论是在元素内部,结合,有时只是,任何想法如何在每个项目之后有评论,当然还有元素之后?