有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

控制台中的java打印Web服务逐行响应

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

<?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.<?xml version="1.0" encoding="UTF-8"?>
2.<loginInformation xmlns="http://www.example.com/restapi" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">

。 . .


共 (1) 个答案

  1. # 1 楼答案

    如果解析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 */));
      }
    }