[英]How to replace null values in XML
I am adding some more tags in xml file by using DOM parser. 我使用DOM解析器在xml文件中添加了一些标签。 I am creating some new tags using DOM parser and want to set their values by passing arraylist.
我正在使用DOM解析器创建一些新标签,并希望通过传递arraylist来设置它们的值。 My arraylist contains values which I am retrieving from database.
我的arraylist包含我从数据库中检索的值。
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. 在这里,我正在创建新标记并在该标记中传递s的值。
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... 我想删除来自数据库到arraylist的null,而不是xml,并获得如上所述的表格请帮助...
The String.valueOf()
is forcing null
to be converted to the String "null"
. String.valueOf()
强制将null
转换为字符串"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): 空字符串
""
也应该发生相同的崩溃(如果你正在使用String做其他事情,这可能很方便):
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"
. 如果
s
为"null"
这应该使节点n
为"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 可能这就是你想要的
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.