JAVA中输入源到字符串的转换

问题描述

我在我的应用程序中使用整个字符串 xml 请求创建了 InputSource 对象,并且我试图从创建的 InputSource 引用中获取整个 xml 请求。请找到下面的代码片段,并建议一些代码/方法来从 InputSource 参考中获取 xmlRequest。

org.xml.sax.InputSource is = new org.xml.sax.InputSource(new StringReader(xmlRequest));

现在我希望从 InputSource 引用 'is' 获取 xmlRequest。

谁能帮我解决这个问题。

解决方法

如果您可以接受从 Reader 重新创建请求,那也很简单:

    InputSource is=new InputSource(new StringReader(xmlRequest));
    Reader r=is.getCharacterStream();
    r.reset(); // Ensure to read the complete String
    StringBuilder b=new StringBuilder();
    int c;
    while((c=r.read())>-1)
        b.appendCodePoint(c);
    r.reset(); // Reset for possible further actions
    String xml=b.toString();
,

您无法从 String 中取回 StringReader。 要么将 xmlRequest 分配给它自己的变量,要么必须创建自己的 StringReader,这样做:

private static class OwnStringReader extends StringReader
{
    private final String content;

    public OwnStringReader(String content)
    {
        super(content);
        this.content=content;
    }

    public String getContent()
    {
        return content;
    }
}

然后您可以通过

检索您的String
    InputSource is=new InputSource(new OwnStringReader(xmlRequest));
    String xml=((OwnStringReader)is.getCharacterStream()).getContent();