在控制台中逐行打印webservice响应

时间:2015-12-23 15:42:08

标签: java xml web-services

我有来自外部供应商的webservice响应。需要在控制台中打印每一行。以下响应存储在响应对象中。

    fetchData: function (sDate, priorDay) {
    store = Ext.getStore('OutOfBalanceList');
    store.reload({
        params: {
            startDate: searchForm.startDate,
            endDate: searchForm.endDate,
            cusip: searchForm.cusip,
            account: searchForm.account
        },
        callback: function (records, options, success) {
            if (records.length == 0) {
                var pdate = priorDay;
                priorDay.setDate(pdate.getDate() - 1);
                sDate.setValue(priorDay);
                searchForm.startDate = Ext.Date.format(sDate.value, 'm/d/Y');
                fetchData(sDate, priorDay);
            }
        }
    });

我的输出应该如下:

<?xml version="1.0" encoding="UTF-8"?>
<loginInformation xmlns="http://www.example.com/restapi" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
  <loginAccounts>
    <loginAccount>
      <accountId>117072</accountId>
      <baseUrl>https://example.net/restapi/v2</baseUrl>
      <email>abc@gmail.com</email>
    </loginAccount>
  </loginAccounts>
</loginInformation>

。 。 。

1 个答案:

答案 0 :(得分:0)

如果解析XML字符串,将其序列化然后将其取回,则可以通过几个步骤完成。试试这段代码:

import com.sun.org.apache.xml.internal.serialize.OutputFormat;
import com.sun.org.apache.xml.internal.serialize.XMLSerializer;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;

final class XmlFormatter {
  private XmlFormatter() { }

  private static Document parse(String in) {
    final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

    try {
      final DocumentBuilder builder = factory.newDocumentBuilder();

      return builder.parse(new InputSource(new StringReader(in)));
    } catch (IOException | ParserConfigurationException | SAXException e) {
      System.err.printf("Something happened here due to: %s", e);
    }
    return null;
  }

  public static String format(final String xml) {
    final Document document = XmlFormatter.parse(xml);
    final OutputFormat format = new OutputFormat(document);
    final Writer out = new StringWriter();
    final XMLSerializer serializer = new XMLSerializer(out, format);

    format.setIndenting(true);
    format.setLineWidth(120);
    format.setIndent(2);

    try {
      serializer.serialize(document);
      return out.toString();
    } catch (IOException e) {
      System.err.printf("Something happened here...this is why: %s", e);
    }
    return null;
  }

  public static void main(final String... args) {
    System.out.printf("%s", XmlFormatter.format(/* YOUR UNFORMATTED XML */));
  }
}
相关问题