classicjonesynz
classicjonesynz

Reputation: 4042

Java XML DocumentBuilderFactory write empty tags <Tag /> from null values

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>.

Upvotes: 0

Views: 2504

Answers (1)

Ian Roberts
Ian Roberts

Reputation: 122364

//add the Category
Element Category = doc.createElement("category");
Rows.appendChild(Category);
if(excel.getCategory() != null){
    Category.appendChild(doc.createTextNode(excel.getCategory()));
}

Here I'm adding the category element to Rows unconditionally, but only adding a text node child if getCategory() is non-null. If it is null, then this will create an empty category element, which will serialize to XML as <category />.

If you want to be able to distinguish in the XML between a null value for excel.getCategory() and an empty string value, then the usual XML schema idiom for that is to make the element "nillable"

<xs:complexType name="data">
    <xs:all>
    <xs:element name="Category" type="xs:string" nillable="true" />
    <!-- other columns.. -->
    </xs:all>
</xs:complexType>

and mark it with xsi:nil

//add the Category
Element Category = doc.createElement("category");
Rows.appendChild(Category);
if(excel.getCategory() != null){
    Category.appendChild(doc.createTextNode(excel.getCategory()));
} else {
    Category.setAttributeNS(XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI,
                            "xsi:nil", "true");
}

This will produce

<category />

when excel.getCategory().equals("") and

<category xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nil="true" />

when excel.getCategory() == null

Upvotes: 1

Related Questions