Skip to content

Commit 9148d9e

Browse files
authored
Part of #360, use xsi:nil for null value with non-pretty writer (#430)
* Part of #360, use xsi:nil for null value with non-pretty writer * Use proper namespace for xsi:nil attribute
1 parent 57aa311 commit 9148d9e

File tree

2 files changed

+18
-1
lines changed

2 files changed

+18
-1
lines changed

src/main/java/com/fasterxml/jackson/dataformat/xml/ser/ToXmlGenerator.java

+8-1
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
import java.math.BigInteger;
66
import java.util.*;
77

8+
import javax.xml.XMLConstants;
89
import javax.xml.namespace.QName;
910
import javax.xml.stream.XMLStreamException;
1011
import javax.xml.stream.XMLStreamWriter;
@@ -1015,7 +1016,13 @@ public void writeNull() throws IOException
10151016
_xmlPrettyPrinter.writeLeafNullElement(_xmlWriter,
10161017
_nextName.getNamespaceURI(), _nextName.getLocalPart());
10171018
} else {
1018-
_xmlWriter.writeEmptyElement(_nextName.getNamespaceURI(), _nextName.getLocalPart());
1019+
if(isEnabled(Feature.WRITE_NULLS_AS_XSI_NIL)) {
1020+
_xmlWriter.writeStartElement(_nextName.getNamespaceURI(), _nextName.getLocalPart());
1021+
_xmlWriter.writeAttribute("xsi", XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI, "nil", "true");
1022+
_xmlWriter.writeEndElement();
1023+
} else {
1024+
_xmlWriter.writeEmptyElement(_nextName.getNamespaceURI(), _nextName.getLocalPart());
1025+
}
10191026
}
10201027
}
10211028
} catch (XMLStreamException e) {

src/test/java/com/fasterxml/jackson/dataformat/xml/ser/TestSerialization.java

+10
Original file line numberDiff line numberDiff line change
@@ -111,6 +111,16 @@ public void testSimpleAttrAndElem() throws IOException
111111
assertEquals("<AttrAndElem id=\"42\"><elem>whatever</elem></AttrAndElem>", xml);
112112
}
113113

114+
public void testNil() throws IOException
115+
{
116+
XmlMapper mapper = new XmlMapper();
117+
mapper.configure(ToXmlGenerator.Feature.WRITE_NULLS_AS_XSI_NIL, true);
118+
WrapperBean<String> bean = new WrapperBean<>(null);
119+
// First, map in a general wrapper
120+
String xml = mapper.writeValueAsString(bean);
121+
assertEquals("<WrapperBean><value xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:nil=\"true\"/></WrapperBean>", xml);
122+
}
123+
114124
@SuppressWarnings("boxing")
115125
public void testMap() throws IOException
116126
{

0 commit comments

Comments
 (0)