如何循环遍历Arraylist <string>并添加到添加到父节点的子节点和子节点

时间:2017-01-23 21:51:44

标签: java xml

我有一个arraylist,需要在xml的子节点中添加列表,并将子节点添加到父节点。我写的下面的代码是正确的吗?

public static String generateXMLData(CouponDetails couponDetails){      
        List<String> list = couponDetails.getCOUPON();      
        String rtrnString = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>"
                +"<Result_Code>"+couponDetails.getSTATUS_CODE()
                +"<Coupons>"+list+"</Coupons>"  
                +"</Result_Code>"
                ;

                return rtrnString;   
    }


@XmlRootElement
public class CouponDetails {

    private String STATUS_CODE;    
    private List<String> COUPON;

    public String getSTATUS_CODE() {        
        if(STATUS_CODE != null){
            return STATUS_CODE;
        }else{
            return "";
        }
    }
    public void setSTATUS_CODE(String sTATUS_CODE) {
        STATUS_CODE = sTATUS_CODE;
    }

    public List<String> getCOUPON() {
        return COUPON;
    }
    public void setCOUPON(List<String> cOUPON) {
        COUPON = cOUPON;
    }
}

在上面的&#34;私人名单COUPON; &#34;是包含xml的String。

1 个答案:

答案 0 :(得分:1)

取决于你想要的。在行

 +"<Coupons>"+list+"</Coupons>"  

您将致电list.toString(),以便获得以下内容: [coupon1,coupon2,coupon3]

或许,您希望在<Coupon></Coupon>代码中包含所有优惠券。您需要在正确的位置关闭</Result_Code>代码。

所以你需要做一些事情:

+"<Coupons>"+list.stream().map((s) -> "<Coupon>" + s + "</Coupon>").collect(Collectors.joining()) +"</Coupons>"

这不好,字符串连接很昂贵,但这可能是修改代码的最小变化。

更好的解决方案是使用StringBuiler,例如:

  public static String generateXMLData(CouponDetails couponDetails) {
    StringBuilder sb = new StringBuilder();
    sb.append("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>")
        .append("<Result_Code>")
        .append(couponDetails.getSTATUS_CODE())
        .append("</Result_Code>")
        .append("<Coupons>");

    for (String coupons : couponDetails.getCOUPON()) {
      sb.append("<Coupon>")
        .append(coupons)
        .append("</Coupon>");
    }
    sb.append("</Coupons>");
    return sb.toString();
  }