JAVA中InputSource到字符串的转换
我已经在应用程序中使用我的整个字符串xml请求创建了InputSource对象,并且我正在尝试从创建的InputSource引用获取整个xml请求。请查找下面的代码片段,并建议从InputSource引用获取xmlRequest的一些代码/方法 org.xml.sax.InputSource is=new org.xml.sax.InputSourcenew StringReaderxmlRequest 现在我希望从InputSource引用“is”获取xmlRequest 有人能帮我吗。你无法从StringReader中取出字符串。 要么将xmlRequest分配给它自己的变量,要么必须创建自己的StringReader,这样做:JAVA中InputSource到字符串的转换,java,xml,string,xml-parsing,saxparser,Java,Xml,String,Xml Parsing,Saxparser,我已经在应用程序中使用我的整个字符串xml请求创建了InputSource对象,并且我正在尝试从创建的InputSource引用获取整个xml请求。请查找下面的代码片段,并建议从InputSource引用获取xmlRequest的一些代码/方法 org.xml.sax.InputSource is=new org.xml.sax.InputSourcenew StringReaderxmlRequest 现在我希望从InputSource引用“is”获取xmlRequest 有人能帮我吗。你无法
private static class OwnStringReader extends StringReader
{
private final String content;
public OwnStringReader(String content)
{
super(content);
this.content=content;
}
public String getContent()
{
return content;
}
}
然后您可以通过
如果您可以接受重新创建来自读者的请求,那么它也很简单:
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();
您无法从StringReader中取出字符串:当然可以。只需读取所有字符,然后附加到StringBuilder,然后从生成器中获取字符串。@user207421但它不是同一个字符串,b读取器必须在之后重置,可能也要在之前重置。
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();