我有一个带有注释nillable = true的变量的类,我不希望它们出现在xml中。该类是从xsd生成的,不能更改。
实施例: 一个看起来像这样的事情的班级:
public class Hi {
...
@XmlElement(name = "hello", nillable = true)
protected Long hello;
...
}
使用JAXBContext创建的marshaller对象进行编组。生成的xml变为:
...
<hello xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nil="true"/>
...
类Hi是从无法更改的xsd生成的。我的问题是,有没有办法让marshaller忽略nillable参数,如果“hello”为null,则不向xml输出任何内容?
答案 0 :(得分:2)
实现此目的的一种方法是实施XMLStreamWriter
类型public class FilteredXMLStreamWriter implements XMLStreamWriter {
private final XMLStreamWriter writer;
private final Set<String> pathsToSkip;
private final Stack<String> path = new Stack<>();
private boolean ignore;
public FilteredXMLStreamWriter(XMLStreamWriter writer, Set<String> pathsToSkip) {
this.writer = writer;
this.pathsToSkip = pathsToSkip;
}
/**
* Build the current path from the Stack
*/
private String toPath() {
StringBuilder sb = new StringBuilder();
boolean first = true;
for (String element : path) {
if (first) {
first = false;
} else {
sb.append('/');
}
sb.append(element);
}
return sb.toString();
}
public void writeStartElement(String prefix, String localName, String namespaceURI)
throws XMLStreamException {
// Add the current
path.push(localName);
if (!ignore) {
this.ignore = pathsToSkip.contains(toPath());
if (!ignore) {
this.writer.writeStartElement(prefix, localName, namespaceURI);
}
}
}
...
public void writeEndElement() throws XMLStreamException {
if (ignore) {
this.ignore = !pathsToSkip.contains(toPath());
} else {
this.writer.writeEndElement();
}
path.pop();
}
...
public void writeCharacters(String text) throws XMLStreamException {
if (!ignore) {
this.writer.writeCharacters(text);
}
}
public void writeCharacters(char[] text, int start, int len)
throws XMLStreamException {
if (!ignore) {
this.writer.writeCharacters(text, start, len);
}
}
...
}
并在其中实施过滤器。
这是一个非常基本和天真的(它没有涵盖很多东西,如命名空间和许多其他东西),可以在你的情况下工作,但它并不意味着完美,它只是意味着表明这个想法:
private static Set<String> pathsToSkip(Class<?> clazz) {
// Make sure that the class is annotated with XmlRootElement
XmlRootElement rootElement = clazz.getAnnotation(XmlRootElement.class);
if (rootElement == null) {
throw new IllegalArgumentException("XmlRootElement is missing");
}
// Create the root name from the annotation or from the class name
String rootName = ("##default".equals(rootElement.name()) ?
clazz.getSimpleName().substring(0, 1).toLowerCase() + clazz.getSimpleName().substring(1) :
rootElement.name());
// Set that will contain all the paths
Set<String> pathsToSkip = new HashSet<>();
addPathsToSkip(rootName, clazz, pathsToSkip);
return pathsToSkip;
}
private static void addPathsToSkip(String parentPath, Class<?> clazz,
Set<String> pathsToSkip) {
// Iterate over all the fields
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
XmlElement xmlElement = field.getAnnotation(XmlElement.class);
if (xmlElement != null) {
// Create the name of the element from the annotation or the field name
String elementName = ("##default".equals(xmlElement.name()) ?
field.getName() :
xmlElement.name());
String path = parentPath + "/" + elementName;
if (xmlElement.nillable()) {
// It is nillable so we add it to the paths to skip
pathsToSkip.add(path);
} else {
// It is not nillable so we check the fields corresponding
// to the field type
addPathsToSkip(path, field.getType(), pathsToSkip);
}
}
}
}
这是一种了解跳过路径的简单方法:
marshaller.marshal(
myObject,
new FilteredXMLStreamWriter(
XMLOutputFactory.newInstance().createXMLStreamWriter(sw),
pathsToSkip(Hi.class)
)
);
然后您将如何称呼它:
<div class="col s12">
<div class="col s12 l2"></div>
<div class="col s12 l2"></div>
<div class="col s12 l4"></div>
<div class="col s12 l2"></div>
<div class="col s12 l2"></div>
</div>
答案 1 :(得分:0)
感谢Nicolas Filotto,我设法根据我的需要让它工作,这里是xmlstreamwriter的最终代码(DelegateXMLStreamWriter只是将调用传递给输入委托):
注意:这仍将打印空白元素,但不会为这些元素写入任何属性或命名空间。我还没有测试过它是否有效,如果父母是可以收费的,但孩子已经设定了。
public class XMLExportStreamWriter extends DelegateXMLStreamWriter {
private Set<String> nillableElements;
private final Stack<String> path = new Stack<>();
private boolean nillable;
private boolean notNull;
private String localName;
private String namespaceURI;
private String prefix;
public XMLExportStreamWriter(XMLStreamWriter delegate) throws XMLStreamException {
super.setDelegate(delegate);
}
public void setNillableElements(Set<String> nillableElements) {
this.nillableElements = nillableElements;
}
@Override
public void writeStartElement(String localName) throws XMLStreamException {
if (!isNillable(localName)) {
super.writeStartElement(localName);
} else {
setElementArgs(null, localName, null);
}
}
@Override
public void writeStartElement(String namespaceURI, String localName) throws XMLStreamException {
if (!isNillable(localName)) {
super.writeStartElement(namespaceURI, localName);
} else {
setElementArgs(null, localName, namespaceURI);
}
}
@Override
public void writeStartElement(String prefix, String localName, String namespaceURI)
throws XMLStreamException {
if (!isNillable(localName)) {
super.writeStartElement(prefix, localName, namespaceURI);
} else {
setElementArgs(prefix, localName, namespaceURI);
}
}
@Override
public void writeEndElement() throws XMLStreamException {
if (!this.nillable || this.notNull) {
super.writeEndElement();
}
this.path.pop();
if (this.nillable) {
this.nillable = this.nillableElements.contains(toPath());
}
}
@Override
public void writeCharacters(String text) throws XMLStreamException {
if (this.nillable) {
if (text != null) {
this.notNull = true;
forceStartElement();
super.writeCharacters(text);
}
} else {
super.writeCharacters(text);
}
}
@Override
public void writeCharacters(char[] text, int start, int len) throws XMLStreamException {
if (this.nillable) {
if (text != null) {
this.notNull = true;
forceStartElement();
super.writeCharacters(text, start, len);
}
} else {
super.writeCharacters(text, start, len);
}
}
@Override
public void writeAttribute(String localName, String value) throws XMLStreamException {
if (!this.nillable) {
super.writeAttribute(localName, value);
}
}
@Override
public void writeAttribute(String namespaceURI, String localName, String value)
throws XMLStreamException {
if (!this.nillable) {
super.writeAttribute(namespaceURI, localName, value);
}
}
@Override
public void writeAttribute(String prefix, String namespaceURI, String localName, String value)
throws XMLStreamException {
if (!this.nillable) {
super.writeAttribute(prefix, namespaceURI, localName, value);
}
}
@Override
public void writeNamespace(String prefix, String namespaceURI) throws XMLStreamException {
if (!this.nillable) {
super.writeNamespace(prefix, namespaceURI);
}
}
private void forceStartElement() throws XMLStreamException {
if (this.prefix != null) {
super.writeStartElement(this.prefix, this.localName, this.namespaceURI);
} else if (this.namespaceURI != null) {
super.writeStartElement(this.namespaceURI, this.localName);
} else {
super.writeStartElement(this.localName);
}
}
private boolean isNillable(String localName) {
this.notNull = false;
this.path.push(localName);
this.nillable = this.nillableElements.contains(toPath());
return this.nillable;
}
private void setElementArgs(String prefix, String localName, String namespaceURI) {
this.prefix = prefix;
this.localName = localName;
this.namespaceURI = namespaceURI;
}
private String toPath() {
StringBuilder sb = new StringBuilder();
boolean first = true;
for (String element : this.path) {
if (first) {
first = false;
} else {
sb.append('/');
}
sb.append(element);
}
return sb.toString();
}
}
我还修改了路径以跳过将集合考虑在内的方法:
private static Set<String> pathsToSkip(Class<?> clazz) {
// Make sure that the class is annotated with XmlRootElement
XmlRootElement rootElement = clazz.getAnnotation(XmlRootElement.class);
if (rootElement == null) {
throw new IllegalArgumentException("XmlRootElement is missing");
}
// Create the root name from the annotation or from the class name
String rootName = ("##default".equals(rootElement.name()) ?
clazz.getSimpleName().substring(0, 1).toLowerCase() + clazz.getSimpleName().substring(1) :
rootElement.name());
// Set that will contain all the paths
Set<String> pathsToSkip = new HashSet<>();
addPathsToSkip(rootName, clazz, pathsToSkip);
return pathsToSkip;
}
private static void addPathsToSkip(String parentPath, Class<?> clazz,
Set<String> pathsToSkip) {
// Iterate over all the fields
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
XmlElement xmlElement = field.getAnnotation(XmlElement.class);
if (xmlElement != null) {
// Create the name of the element from the annotation or the field name
String elementName = ("##default".equals(xmlElement.name()) ?
field.getName() :
xmlElement.name());
String path = parentPath + "/" + elementName;
if (xmlElement.nillable()) {
// It is nillable so we add it to the paths to skip
pathsToSkip.add(path);
} else {
// It is not nillable so we check the fields corresponding
// to the field type
// If it's a collection we need to get the generic type
if (Collection.class.isAssignableFrom(field.getType())) {
ParameterizedType fieldGenericType = (ParameterizedType) field
.getGenericType();
Class<?> fieldGenericTypeClass = (Class<?>) fieldGenericType
.getActualTypeArguments()[0];
addPathsToSkip(path, fieldGenericTypeClass, pathsToSkip);
} else {
addPathsToSkip(path, field.getType(), pathsToSkip);
}
}
}
}
}
它被称为:
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(new File(filePath)));
XMLExportStreamWriter exportStreamWriter = new XMLExportStreamWriter(XMLOutputFactory.newInstance().createXMLStreamWriter(
bufferedWriter);
exportStreamWriter.setNillableElements(getNillablePaths(MyClass.class));