2017-09-11 50 views
0

我正在使用下面提到的代码在arraylist的xml中编写逗号分隔值。替换XML中的空值

String commaSeparated = String.join(",", list); 
Element n= doc.createElement("value"); 
n.appendChild(doc.createTextNode(commaSeparated)); 

我的ArrayList中包含的表示如下一些空值:

<value>1,2,3,null,4,5,null,6</value> 

我想通过一些其他的值来代替这个空说“一”。

我使用下面的代码来做到这一点:

if(commaSeparated==null){ 
commaSeparated="a"; 
} 

但还是我得到空值,而不是预期的输出。

预期输出:

<value>1,2,3,a,4,5,a,6</value> 

请帮

+0

很难知道,因为相关的代码是不完整的,但我的猜测是,“空”(一个字符串值)是不一样的空。 – jdv

回答

0

你应该尝试改变:

if(commaSeparated==null){ // the complete string is not null 
    commaSeparated="a"; //never reached 
} 

commaSeparated=commaSeparated.replaceAll("null","a"); //replaces all null substrings with 'a' 
0

一些解释 - 你可能错过了逗号分隔我这是最后一个字符串,其值由逗号分隔。所以试图找出它是否为空并不是真正的解决方案。

您可以在最终字符串上执行此操作,或者可以检查列表中的每个元素,并在预期的时间使用您自己的值创建新的元素。即

List<String> formattedList = new ArrayList<String>(); 
for (String element : list) { 
    if(element == null){ 
     formattedList.add("a"); 
    }else{ 
     formattedList.add(element); 
    } 
} 

现在你可以把formattedListString.join

0

尝试之前更换空值,对于为例:

list.replaceAll(s -> s == null ? "a" : s); 
    String commaSeparated =String.join(",", list);