如何在 React Native 中访问 xml 静态资源

问题描述

我想向我的 React Native 项目添加一个静态 xml 资产,并像访问图像一样访问它。

添加

  resolver: {
    assetExts: ['png','xml'],},

到metro.config.js,const asset = require('asset.xml') 返回一个数字。但是如何从这个号码中获取文件内容呢?

下面的代码在开发模式下为我提供了一个 URI,我可以使用 axios 来获取它,但在发布模式下它只返回一个asset 这样的文件名,如何在发布模式下读取它?

 Image.resolveAssetSource(asset).uri;

解决方法

您可以使用 expo-asset 获取 CREATE TEMPORARY TABLE etl.tmp1 as select * from tab limit 10; select count(*) from etl.tmp1 ;

localUri

然后你可以使用 expo-file-system 以字符串的形式获取文件的内容:

const [{ localUri }] = await Asset.loadAsync(require('path/to/your/asset.xml'))

然后就可以将xml字符串转换成带有fast-xml-parser这样的包的JS对象。

为了使其工作,您应该像上面提到的那样编辑您的 const xmlString = FileSystem.readAsStringAsync(localUri) ,即:metro.config.js 数组应包含 assetExts

另外,如果你使用Typescript,你应该添加一个声明文件,比如xml,内容为:

xml.d.ts

并且该声明文件应位于一个文件夹中,该文件夹已添加到 declare module '*.xml' { const moduleId: number; // the react-native import reference export default moduleId; } 中的 typeRoots 属性。

提醒一下:您可以在裸露的本机应用程序中使用没有 Expo 的解决方案,您只需要安装上面链接中描述的 unimodules。

祝你好运! :)