React native, import and read local xml file
Asked Answered
P

2

6

I'm new to React Native framework. I'm trying to use it for make a cross-platform mobile app. I want to open and read a local XML file, present in my app folder, but I can't work out how to do this.

My biggest problem at the moment is how to assign this local XML file to a variable, I've tried with the require command, or with import, but these commands haven't worked.

Preserve answered 25/11, 2017 at 9:47 Comment(1)
Having the same issue, @Nicolo did you find a solution?Amitie
P
0

You need to transform your xml file to a javascript object, so that you can work with it. Maybe you could use react-native-xml2js

Punjabi answered 25/11, 2017 at 9:57 Comment(2)
thanks for your answer, but for now I don't jet resolve my problem. I'm trying this code : var RNFS = require('react-native-fs'), xml2js = require('react-native-xml2js'); RNFS.readFile(..... My problem is that I'm not able to pass the path of my project directory where are saved the xml that I would parseCipolin
@NicolòMazzoli did you manage to fix this issue, if so please post your solution..Supposed
C
0

the easiest way you can do this is by doing this:

  • switch the xml from .xml to .js
  • make the whole content of the file as a string and put it inside a variable (use `` to select multiple lines)
  • add at the end of your .js file (the one u just changed from .xml):

export default ;

  • this will assure to export the variable as the main element of this file and then where u want to access the content the file just use :

import from '<fileName(without extension)>'

  • then u can use the variable containing your xml file as a text you can convert it to a json then parse it so u can have a valid json which is pretty flexible to work with

your code should look somthing like this:

xmlFile.js (used to be xmlFile.xml):

const xmlData = `<note>

<from>Jani</from>

<to>Tove</to>

<message>Remember me this weekend</message>

</note>`

export default xmlData;

file.js:

import xmlJs from 'xml-js';//import the library that handle xml/js conversion

import xmlData from './xmlFile';//getting the text

const jsontext = xmlJs.xml2json(xmlData)//turning it into a json formated text

const jsonObj = JSON.parse(jsontext)//parsing it into a json Object

best of luck

Climactic answered 20/5 at 5:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.