Hey so I’m wondering how it is possible to write a empty tag for example <Category /> with the DocumentBuilderFactory (based off this resource, library javax.xml.parsers.*;), as for the moment I’m having to apply an if condition if object.getCategory() != null then create the Category Tag otherwise ignore it.
//add the Category
if(excel.getCategory() != null){
Element Category = doc.createElement("category");
Category.appendChild(doc.createTextNode(excel.getCategory()));
Rows.appendChild(Category);
}
And Schema
<xs:complexType name="data">
<xs:all>
<xs:element name="Category" type="xs:string" minOccurs="1" />
<!-- other columns.. -->
</xs:all>
</xs:complexType>
And I’ve noticed if I add a textnode that is null, the transformer.transform(source, result); will return with a heap of NullException errors. Is there a way to configure the transformer to know that the TextNode is intentionally left empty? and in turn create <Category /> or <Category></Category>.
Here I’m adding the
categoryelement toRowsunconditionally, but only adding a text node child ifgetCategory()is non-null. If it is null, then this will create an emptycategoryelement, which will serialize to XML as<category />.If you want to be able to distinguish in the XML between a
nullvalue forexcel.getCategory()and an empty string value, then the usual XML schema idiom for that is to make the element “nillable”and mark it with
xsi:nilThis will produce
when
excel.getCategory().equals("")andwhen
excel.getCategory() == null