使用JAXB格式化XML [英] Formatting XML with JAXB
问题描述
我一直试图找到一个类似的回答问题,但我没有运气。
I've been trying to find a similar answered question but I haven't had any luck.
我基本上需要从文本文件中读取一些数据然后将其编组为XML。正常格式化,创建
I basically need to read some data off a text file and then marshal it to XML. Normal formatting though, creates
<title></title>
字段等,而我想要的是每个字段都有这种格式:
fields etc. while what I want is every field to have this format:
<field name="title"></field>.
title这里只是一个占位符,我想要的是name属性有变量它所绑定的名称,所以
"title" here is just a placeholder, what I want is for the name attribute to have the variable name which it is bound, so
<title>
变为
<field name="title">
,
<author>
变为
<field name="author"> etc.
我猜这与我没有得到的注释有关。
I'm guessing it has something to do with the annotations that I'm not getting.
我的文档类结构简单,比如
My document class has a simple structure, like
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Document
{
private Integer id;
private String content;
private String title;
private String author;
private String b;
}
推荐答案
每个XML元素(不属性) )在JAXB中是一个Java类。
并且属性可以是属性。
所以你必须有类似的东西:
Each XML element (not attribute) in JAXB is a Java class. And attribute can be a property. So you have to have something like:
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Document
{
@XmlElement(name = "field")
private List<Field> field = new ArrayList<>();
}
和
@XmlType()
public class Field
{
@XmlAttribute(name="name", required="true")
private String name;
@XmlValue
private Object value;
}
实际上 私有对象值;
转换为 XML anyType
,这样您就可以将其设置为 Integer
for id
, String
for content
等
Actually private Object value;
translates to XML anyType
so you will be able to set it to Integer
for id
, String
for content
etc.
将您当前的文档
类封送到XML格式为
BTW your current Document
class marshalls to XML as
<Document>
<id></id>
<content></content>
<title></title>
<author></author>
<b></b>
<Document>
这篇关于使用JAXB格式化XML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!