如何将 inputsource 转换为 inputstream 并将其作为参数提供给 stringreader?

How to convert inputsource to inputstream which will feed to stringreader as the parameter?

我有要求,我需要从服务器获取 xml 以解析它是否存在,如果不存在则从资产文件夹中获取文件。

无论 xml 我正在使用输入流,我将它作为参数传递给 StringReader 以进行进一步处理。我正在使用 XmlPullParser 进行解析。

但我无法将 inputsource 参数传递给 stringreader 以进行进一步解析。我不使用文档 reader。请找到下面的代码。

 private void  readSynconfiguration( )
    {

        XmlParser xmlparser = new XmlParser();

            try {
                String strFromMbo = getDataFromMBO();
                if(strFromMbo != null && !strFromMbo.isEmpty()) {   // first
                    InputSource is = new InputSource(new StringReader(strFromMbo));
                   // result = getStringFromInputStream(is);
                }
                else {
                    context = RetailExecutionApplication.getApp().getApplicationContext();
                    InputStream stream = context.getAssets().open("syncSettings.xml");
                    result = getStringFromInputStream(stream);
                }
            } catch (IOException e) {
                syncSetting = false;
                e.printStackTrace();
            }

        StringReader labelReader = new StringReader(result);

        try {
            if(syncSetting) {
                labelSharedInstance.clear();
                labelSyncDetails = xmlparser.LabelsParse(labelReader);
                labelSharedInstance = labelSyncDetails;
            }
        } catch (XmlPullParserException e) {
            syncSetting = false;
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

请在这方面帮助我。

You can not pass inputsorce object directly to StringReader. First of all you convert inputsorce to reader as follows :

Reader reader = yourInputSource.getCharacterStream();
String result = reader.toString();

StringReader labelReader = new StringReader(结果);

我觉得你把事情弄糊涂了。 XmlPullParser.setInput() 方法采用 Reader,因此这就是您需要提供的内容。

在情况 1(来自数据库)中,您在 strFromMbo 中有一个字符串,因此只需用 StringReader.

包装

情况 2(来自文件),您有两个选择:

  • 将整个文件作为字符串加载到内存中。这就是你正在做的。
  • 使用 FileReader。使用更少的内存。

在这两种情况下,请记住关闭您的资源。

我不明白 "inputsource" 和什么有什么关系。

String xml = getDataFromMBO();
if (xml == null || xml.isEmpty()) {
    context = RetailExecutionApplication.getApp().getApplicationContext();
    try (InputStream stream = context.getAssets().open("syncSettings.xml")) {
        xml = getStringFromInputStream(stream);
    } catch (IOException e) {
        syncSetting = false;
        e.printStackTrace();
    }
}

if (syncSetting) {
    try {
        labelSharedInstance.clear();
        labelSyncDetails = new XmlParser().LabelsParse(new StringReader(xml));
        labelSharedInstance = labelSyncDetails;
    } catch (XmlPullParserException e) {
        syncSetting = false;
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}