I am adding some more tags in xml file by using DOM parser. I am creating some new tags using DOM parser and want to set their values by passing arraylist. My arraylist contains values which I am retrieving from database.
My code is a follows:
loading file using dom parser
for(String s:a.List){
Element n= doc.createElement("value");
n.appendChild(doc.createTextNode(String.valueOf(s)));
}
here I am creating new tag and passing values of s in that tag.
Output I am getting:
<value>1</value>
<value>2</value>
<value>3</value>
<value>null</value>
<value>null</value>
<value>4</value>
; ; so on
Expected output:
<value>1</value>
<value>2</value>
<value>3</value>
<value/>
<value/>
<value>4<value>
I want to remove null which is coming from databse to arraylist and than to xml and get form as mentioned above Please help...
The String.valueOf()
is forcing null
to be converted to the String "null"
. Just remove that conversion and the null tags will collapse:
for(String s : a.List){
Element n = doc.createElement("value");
n.appendChild(doc.createTextNode(s)); // null renders as empty
}
The same collapsing should happen for empty Strings ""
(which might be convenient if you're doing something else with the String too):
for(String s : a.List){
Element n = doc.createElement("value");
if(s == null) { s = ""; } // force nulls to be empty Strings
n.appendChild(doc.createTextNode(s));
}
...or you can conditionally omit the child (which also creates a collapsed tag):
for(String s : a.List){
Element n = doc.createElement("value");
if(s != null) {
n.appendChild(doc.createTextNode(s)); // only append non-null values
}
}
If you wanted to omit the tag entirely you could do this:
for(String s : a.List){
if(s != null) {
Element n = doc.createElement("value");
n.appendChild(doc.createTextNode(s));
}
}
Would this work for you?
String value = String.valueOf(s);
if (! 'null'.equals(value)) { n.appendChild(doc.createTextNode(value)); }
This should leave the node n
empty if s
is "null"
.
I have try below code:
for(String b:a)
{
Element valuesElements = doc.createElement("values");
if(b!=null)
{
valuesElements.appendChild(doc.createTextNode(b));
}
rootElement.appendChild(valuesElements);
}
and get below result:
<root><values>a</values><values/></root>
Probably this is what you want
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.