2015-11-04 52 views
0

我有一個要求來解析具有重複元素的XML數據,並連接所有用逗號分隔的數組列表。用逗號分隔的arraylist連接

我想要的O/P串像約翰,john1,john2,john3,j​​ohn4但我得到我的輸出:約翰,John1,John2,John3,John4,

package eclipsepackage; 
import javax.xml.parsers.*; 
import org.xml.sax.InputSource; 
import org.w3c.dom.*; 
import java.io.*; 
import java.util.ArrayList; 


public class xmlparserclass { 

public static void main(String[] args) { 
    String xmlRecords = 
       "<data>" + 
       " <service_add>" + 
       " <service_cd>John</service_cd>" + 
       " <service_cd>John1</service_cd>" + 
       " <service_cd>John2</service_cd>" + 
       " <service_cd>John3</service_cd>" + 
       " <service_cd>John4</service_cd>" + 
       " </service_add>" + 
       "</data>"; 

      try { 
       DocumentBuilderFactory dbf = 
        DocumentBuilderFactory.newInstance(); 
       DocumentBuilder db = dbf.newDocumentBuilder(); 
       InputSource is = new InputSource(); 
       is.setCharacterStream(new StringReader(xmlRecords)); 

       Document doc = db.parse(is); 

       NodeList nPanList = doc.getElementsByTagName("service_add"); 

       for(int temp = 0 ; temp <nPanList.getLength(); temp++){ 
       Node nNode = nPanList.item(temp); 
       Element eElement = (Element) nNode; 
       NodeList childList = eElement.getChildNodes(); 
       String [] sPANNO = new String[childList.getLength()] ; 
       ArrayList list = new ArrayList(); 
       for(int i = 0; i < childList.getLength(); i++){ 
       Node childNode = childList.item(i); 
       list.add(childNode.getTextContent());     
       } 

       if (list.size() >= 1) { 
        System.out.print(list.get(0)); 
       } 
       for (int i = 1; i < list.size(); i++) { 
        System.out.print(", " + list.get(i)); 
       } 
       } 

      } 
      catch (Exception e) { 
       e.printStackTrace(); 
      } 
    } 
    } 
+2

您確定您存儲在ArrayList中的文本元素不包含任何逗號嗎? – Ankur

+0

謝謝,我意識到自己的文字中有一些空格。 –

回答

0

我刪除了雙引號後的空格,然後它工作。所有文本元素都以逗號分隔連接。