【问题标题】:How to read XML files in flutter?如何在 Flutter 中读取 XML 文件?
【发布时间】:2021-11-24 17:58:16
【问题描述】:

我正在尝试在我的颤振中读取 XML 文件。但是每次我尝试读取文件时,它只会抛出一个错误。

这是我读取 xml 文件的地方(我的 XML 文件很大)。

convertXMLtoJSON() async {
File file = File('assets/xml_file/belovedskincare.xml');
Future<String> xml = file.readAsString();
}

当我运行它时,它会抛出这个错误。

E/flutter (13956): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: FileSystemException: Cannot open file, path = 'assets/xml_file/belovedskincare.xml' (OS Error: No such file or directory, errno = 2)

我也尝试了其他一些功能,例如

file.readAsLines();
file.readAsStringSync();

但什么都没有改变。

这是我的 pubspec.yaml

资产运行良好。您可以在第二张图片中看到左侧的文件结构。

我也尝试过rootbundle,但效果不佳。

convertXMLtoJSON() async {
String file = await rootBundle.loadString('assets/xml_file/belovedskincare.xml');
print(file);
}

当我运行这个时,它显示了这个错误。

E/flutter (13956): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: Null check operator used on a null value  

【问题讨论】:

    标签: xml flutter


    【解决方案1】:

    对于 AssetBundle,您必须在主类中添加 WidgetsFlutterBinding.ensureInitialized(); 行。

    这是我的主要课程,

        void main() {
      WidgetsFlutterBinding.ensureInitialized();
      FetchData a = FetchData();
      a.data();
      runApp(const MyApp());
    }
    

    这是我加载我的 XML 文件的地方,

        class FetchData {
      data() async {
        print(await rootBundle.loadString("assets/xml_file/belovedskincare.xml"));
      }
    }
    

    如果要将 XML 文件转换为 JSON,可以使用xml2json package

    class FetchData {
      data() async {  
      final xml = await rootBundle.loadString("assets/xml_file/belovedskincare.xml");
      Xml2Json xml2json = Xml2Json();
      xml2json.parse(xml);
      var json = xml2json.toGData();
      print(json);
      }
    }
    

    至于file.readAsString();,我还在努力解决问题。

        convertXMLtoJSON() async {
    File file = File('assets/xml_file/belovedskincare.xml');
    Future<String> xml = file.readAsString();  // this is where the error happens
    }
    

    您也可以使用 localhost 来读取文件(我使用的是 XAMPP)。将 XML 文件放在 htdocs 目录中并使用http package 来读取文件。 对于 WAMP,将文件放在 www 目录中。

    这是我的代码, 将 URL 中的 localhost 替换为您的 IP 地址。在命令提示符中输入ipconfig 以获取您的 IP 地址(IPv4 地址)。

    并使用xml2json package 将 XML 文件转换为 JSON 格式。

        final jsonData =
          await http.get(Uri.parse('http://localhost/file_name'));
      final xml = jsonData.body;
      Xml2Json xml2json = Xml2Json();
      xml2json.parse(xml);
      var json = xml2json.toGData();
      print(json);
      var response = jsonDecode(jsonEncode(json));
      print(response);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多