Skip to content

Commit

Permalink
Part of #360, use xsi:nil for null value with non-pretty writer (#430)
Browse files Browse the repository at this point in the history
* Part of #360, use xsi:nil for null value with non-pretty writer

* Use proper namespace for xsi:nil attribute
  • Loading branch information
Migwel authored Nov 11, 2020
1 parent 57aa311 commit 9148d9e
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import java.math.BigInteger;
import java.util.*;

import javax.xml.XMLConstants;
import javax.xml.namespace.QName;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;
Expand Down Expand Up @@ -1015,7 +1016,13 @@ public void writeNull() throws IOException
_xmlPrettyPrinter.writeLeafNullElement(_xmlWriter,
_nextName.getNamespaceURI(), _nextName.getLocalPart());
} else {
_xmlWriter.writeEmptyElement(_nextName.getNamespaceURI(), _nextName.getLocalPart());
if(isEnabled(Feature.WRITE_NULLS_AS_XSI_NIL)) {
_xmlWriter.writeStartElement(_nextName.getNamespaceURI(), _nextName.getLocalPart());
_xmlWriter.writeAttribute("xsi", XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI, "nil", "true");
_xmlWriter.writeEndElement();
} else {
_xmlWriter.writeEmptyElement(_nextName.getNamespaceURI(), _nextName.getLocalPart());
}
}
}
} catch (XMLStreamException e) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,16 @@ public void testSimpleAttrAndElem() throws IOException
assertEquals("<AttrAndElem id=\"42\"><elem>whatever</elem></AttrAndElem>", xml);
}

public void testNil() throws IOException
{
XmlMapper mapper = new XmlMapper();
mapper.configure(ToXmlGenerator.Feature.WRITE_NULLS_AS_XSI_NIL, true);
WrapperBean<String> bean = new WrapperBean<>(null);
// First, map in a general wrapper
String xml = mapper.writeValueAsString(bean);
assertEquals("<WrapperBean><value xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:nil=\"true\"/></WrapperBean>", xml);
}

@SuppressWarnings("boxing")
public void testMap() throws IOException
{
Expand Down

0 comments on commit 9148d9e

Please sign in to comment.