【问题标题】:Convert a String or a InputStreamReader into InputSource将 String 或 InputStreamReader 转换为 InputSource
【发布时间】:2010-10-10 11:12:41
【问题描述】:

我刚刚阅读了一些教程,以便解析来自网络的 xml 提要并将它们转换为 Listview:

URL file = new URL("http://..../file.xml"); 
SAXParserFactory fabrique = SAXParserFactory.newInstance();
SAXParser parseur = fabrique.newSAXParser();
XMLReader xr = parseur.getXMLReader(); 
ReglageParseur gestionnaire = new ReglageParseur();
xr.setContentHandler(gestionnaire);
xr.parse(new InputSource(file.openStream()));

一切都很好,我可以解析 xml。

我的第二步是将 web 上的 xml 文件存储到手机上的 xml 文件中,并且仅在用户询问时更新它。 (事实上​​,这个xml文件应该不会改变,或者可能每6个月一次,所以我不想每次都下载它。)

所以,我所做的是将文件存储在手机上并根据用户需求进行更新。

我可以通过这样做来阅读它:

fIn = openFileInput("fichier.xml");
InputStreamReader isr = new InputStreamReader(fIn);
char[] inputBuffer = new char[255];
isr.read(inputBuffer);
String readString = new String(inputBuffer);

所以,就目前而言,一切似乎都很好,我几乎很高兴。

问题是现在我要解析手机上的新文件时:

xr.parse(InputSource);

我需要一个 InputSource 作为参数。

所以我的问题是:

如何将手机中的文件转换为 InputSource? 我成功拥有了 InputStreamReader 或 String,但想将其转换为 InputSource。

非常感谢您的宝贵帮助

【问题讨论】:

    标签: android xml


    【解决方案1】:

    好吧,我不知道 Android 版本上有哪些构造函数,但是 J2SE InputSource class 有一个带有 Reader 参数的构造函数。你试过吗?

    另外,为什么不直接从InputStream 构造一个 InputSource?我假设fInFileInputStream?为什么不直接打电话:

    InputSource input = new InputSource(fIn);
    

    ?

    【讨论】:

    • 非常感谢,我刚刚找到 InputSource input = new InputSource(new StringReader(readString));但你的答案真的更好!
    • 哎呀我做了很愚蠢的事情!非常感谢让我大开眼界!愚蠢的问题:-p
    【解决方案2】:

    最适合我将字符串转换为 InputSource 的行是:

    String myStringObject = "Hello this is string object to convert in InputSource";
    InputSource inSource =  new InputSource(new StringReader(myStringObject));
    

    【讨论】:

      猜你喜欢
      • 2010-09-19
      • 2013-06-11
      • 2012-12-24
      • 1970-01-01
      • 2014-05-16
      • 2011-01-26
      • 2011-03-10
      • 2023-03-26
      相关资源
      最近更新 更多