Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create an XML text node with an empty string value (in Java)

Tags:

java

xml

I am using a Transform object to save my XML file but it seems to drop empty text nodes. Is there any way to create (and keep) a text node with an empty string i.e. "".

Here is how I create the node:

Element type = doc.createElement("TYPE");

type.appendChild(doc.createTextNode(value));

It is just that sometimes value is an empty string "". When I look at the XML with a text editor I see

<TYPE />

instead of

<TYPE></TYPE>

After I read this XML file back in and traverse the nodes the <TYPE> element simply doesn't have any children even though I explicitly created one #text node for it!

EDIT - Happy Thanksgiving (for my fellow Canadians)

Important note, I am not working from a known set of tags, rather the program I am working on uses the presence of a text node to assign a JTextField to the GUI. It is just that sometimes the field is left empty (not null but ""). When I store that field and then read it back the GUI doesn't render the JTextField anymore because there is no text node. So I am looking at ways to create an XML document that creates a text node even if there is nothing in it. If that simply can't be done with XML then I will have to use an attribute to mark tags that are editable (somewhat like Andrey Breslav suggested) and so should have a JTextField assigned.

I will try Mads Hansen's suggestion of a non-breaking space.

like image 568
BigMac66 Avatar asked Oct 07 '10 18:10

BigMac66


People also ask

How do you write an element XML with no content?

"Empty XML Elements An element with no content is said to be empty. In XML, you can indicate an empty element like this: <element></element> or you can use an empty tag, like this (this sort of element syntax is called self-closing): <element /> The two forms above produce identical results in an XML parser."

Can an XML tag be empty?

Empty XML ElementsAn element with no content is said to be empty. The two forms produce identical results in XML software (Readers, Parsers, Browsers). Empty elements can have attributes.


3 Answers

A text node without text is not a text node.

If you are trying to control how the XML element is serialized, <TYPE/> and <TYPE></TYPE> are equivalent, and it will not matter to an XML processor if either was used. Both are declaring a TYPE element without any text(). Most processors will serialize an empty element as a self-closing element.

If you really want to prevent the element from being serialized as self-closing, you could get cute and add a zero-width space as the text node value: <TYPE>&#x200B;</TYPE> which will look like: <TYPE></TYPE>.

It isn't technically an "empty" string, but might achieve what you want, and will not pad with space if the text node is selected and used.

like image 170
Mads Hansen Avatar answered Oct 17 '22 23:10

Mads Hansen


From an XML point of view, there is no difference between <TYPE/> and <TYPE></TYPE>. There are both equivalent and can be used interchangeably. For an XML parser it means, that there is no text. The parser doesn't distinguish between "no text" and a "zero length text".

In contrast Java's null and "" are totally different concepts.

So if you want to map from Java values to XML and vice versa you have to handle that mismatch. And there are several possible alternatives. For example you can abandon null values for your String variables. Then you have to ensure, that all your String variables are initialized with empty strings. Or you can say a TYPE element without a text child (serialized as <TYPE/> or <TYPE></TYPE>) means the empty string in Java and a missing TYPE element stands for null. It's your choice.

like image 33
vanje Avatar answered Oct 18 '22 01:10

vanje


Here is the code for what you are looking for:

try{
    DocumentBuilderFactory docFactory=DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder=docFactory.newDocumentBuilder();

    //root Elements -- Response
    Document doc=docBuilder.newDocument();
    doc.setXmlStandalone(true);
    Element response=doc.createElement("Data");
    doc.appendChild(response);

    // Child Element -- Play
    Element hangup=doc.createElement("Type");
    response.appendChild(hangup);

    //Writer the content into xml file
    TransformerFactory transformerFactory=TransformerFactory.newInstance();
    Transformer transformer=transformerFactory.newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT,"yes");

    DOMSource source=new DOMSource(doc);
    StreamResult result=new StreamResult(sayOut);
    //StreamResult result=new StreamResult(System.out);

    transformer.transform(source,result);
    logger.info("===========XML GENERATION DON FOR HANGUP============");

}catch(ParserConfigurationException pce){
    logger.error(" ==============2======== ERROR IN PRASERCONFIGURATION ===================================");
    pce.printStackTrace();
}

Output Generated By It:

<?xml version="1.0" encoding="UTF-8"?>
<Data>
<Type/>
</Data>

Hope I have given right thing... although I agree with that <Type/> or <Type></Type> has no difference with respect to XML Parser.

like image 2
pkm1986 Avatar answered Oct 18 '22 01:10

pkm1986