【问题标题】:Getting the content of an xml file and storing the content to a string in order to parse the content获取 xml 文件的内容并将内容存储到字符串中以解析内容
【发布时间】:2014-09-08 08:37:41
【问题描述】:

我尝试在 return 语句之前放一个 toast,但 String 变量返回一个空字符串。

public String getXmlFile(String pathFile, Context context){

      String xmlFileString = "";
      AssetManager am = context.getAssets();
      try {
        InputStream str = am.open(pathFile);
        int length = str.available();
        byte[] data = new byte[length];
        xmlFileString = new String(data);
      } catch (IOException e1) {
            e1.printStackTrace();
      }

       return xmlFileString;
}

【问题讨论】:

  • 因为你从来没有从流中读取
  • 你没有把InputStream读成data
  • 我已经发布了答案,试试吧..

标签: java android xml parsing


【解决方案1】:

用这个从InputStream读取byte[]

public byte[] convertStreamToString(InputStream is) throws Exception {
    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder();
    String line = null;
    while ((line = reader.readLine()) != null) {
        sb.append(line);
    }
    is.close();

    return sb.toString().getBytes("UTF-8");
}

【讨论】:

    【解决方案2】:

    使用它来读取 XML。如果不将 UTF-8 传递给 InputStreamReader,您可能会得到一个损坏的 XML 字符串。

    BufferedReader reader = new BufferedReader(new InputStreamReader(
        context.getAssets().open(pathFile), HTTP.UTF_8));
    StringBuilder sb = new StringBuilder();
    String line;
    while ((line = reader.readLine()) != null) {
        sb.append(line);
    }
    reader.close();
    

    现在,在我将字符串解析为 XML 时,还存在每个换行符都被解释为自己的 XML 节点的问题。空间也是一个问题。在上面读取的字符串上使用它来解决这个问题:

    String oneLineXml = sb.toString().replace("\n", "").replaceAll("> +<", "><");
    

    只有这样你才应该解析字符串,像这样:

    Document xml = DocumentBuilderFactory.newInstance().newDocumentBuilder()
        .parse(new InputSource(new ByteArrayInputStream(
            oneLineXml.getBytes(HTTP.UTF_8))));
    

    【讨论】:

      猜你喜欢
      • 2014-09-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-27
      • 2013-06-18
      • 1970-01-01
      相关资源
      最近更新 更多