7

I tried read xml file and parse it with react-xml-parser library.

 var XMLParser = require('react-xml-parser');
 var xml = new XMLParser().parseFromString(xml_string);
 console.log(xml);
 console.log(xml.getElementsByTagName('Row'));

Here, it should read from string, but I need get it from file. My xml file is located in directory: xmldata/list.xml, so I don't now how to do that.


tried this code:

import XMLData from '../../xmldata/list.xml';
function ReadData() {
          var jsonDataFromXml = new XMLParser().parseFromString(XMLData);
          console.log(jsonDataFromXml);
          console.log(jsonDataFromXml.getElementsByTagName('Row'));

        }
    }
}

structure folder

-src
   |—views
        |—AdminScreen
               |—AdminScreen.js <-here used list.xml
   |—xmldata
           |—list.xml 

but result is:

bundle.js:81 Uncaught TypeError: Cannot set property 'value' of undefined
    at bundle.js:81
    at Array.map (<anonymous>)
    at e.value (bundle.js:76)
    at e.value (bundle.js:148)
    at ReadData (AdminScreen.js:36)
    at AdminScreen (AdminScreen.js:14)
    at renderWithHooks (react-dom.development.js:15821)
    at mountIndeterminateComponent (react-dom.development.js:18141)
    at beginWork$1 (react-dom.development.js:19357)
    at HTMLUnknownElement.callCallback (react-dom.development.js:363)
    at Object.invokeGuardedCallbackDev (react-dom.development.js:412)
    at invokeGuardedCallback (react-dom.development.js:466)
    at beginWork$$1 (react-dom.development.js:24570)
    at performUnitOfWork (react-dom.development.js:23505)
    at workLoopSync (react-dom.development.js:23480)
    at renderRoot (react-dom.development.js:23155)
    at scheduleUpdateOnFiber (react-dom.development.js:22653)
    at scheduleRootUpdate (react-dom.development.js:25686)
    at updateContainerAtExpirationTime (react-dom.development.js:25712)
    at updateContainer (react-dom.development.js:25812)
    at react-dom.development.js:26370
    at unbatchedUpdates (react-dom.development.js:22952)
    at legacyRenderSubtreeIntoContainer (react-dom.development.js:26369)
    at Object.render (react-dom.development.js:26460)
    at Module../src/index.js (index.js:30)
    at __webpack_require__ (bootstrap:785)
    at fn (bootstrap:150)
    at Object.0 (index.js:2)
    at __webpack_require__ (bootstrap:785)
    at checkDeferredModules (bootstrap:45)
    at Array.webpackJsonpCallback [as push] (bootstrap:32)
    at main.chunk.js:1

4 Answers 4

8

To read a local file you have two options either you can use XMLHttpRequest or axios.

Using XMlHttpRequest:

import XMLData from "../../xmldata/list.xml";

var rawFile = new XMLHttpRequest();
rawFile.open("GET", XMLData, false);
rawFile.onreadystatechange = () => {
    if (rawFile.readyState === 4) {
        if (rawFile.status === 200 || rawFile.status == 0) {
            var xmlasstring = rawFile.responseText;
            console.log('Your xml file as string', xmlasstring)
        }
    }
}

I would recommend using axios because it is more convenient and better option when working with React JS.

Using axios:

import XMLData from "../../xmldata/list.xml";

axios.get(XMLData, {
   "Content-Type": "application/xml; charset=utf-8"
})
.then((response) => {
   console.log("Your xml file as string", response.data);
});

Now after getting your XML you can make object or JSON if you want by using npm packages like react-xml-parser, xml2js. I would recommend using xml2js it's nice. And I believe now you can also send 'POST' request in order to update your XML if you want.

Sign up to request clarification or add additional context in comments.

Comments

4

If your data comes from back-end then you can directly use that data as xml_data.But in your case you are trying to import data from .XML file but i have not found any way to access XML file direct in react.

Solution:

You need to create xml_data.js file like below which import your XML data

const xml_data = `<?xml version='1.0' encoding='utf-8'?>
<?xml-stylesheet type="text/xsl" href="ACSPIXMT.xsl" ?>

<Library>
   <Books count='1'>
       <Book id='1'>
           <Name>Me Before You</Name>
           <Author>Jojo Moyes</Author>
       </Book>
   </Books>
   <Music count=1>
       <CD id='2'>
           <Name>Houses of the Holy</Name>
           <Artist>Led Zeppelin</Artist>
       </CD>
   </Music>
</Library>`

export default xml_data;


Import xml_data from 'path of your xml file';
var xml = new XMLParser().parseFromString(xml_data);

2 Comments

Thx @Prakash-karena, Here returns error : Cannot set property 'value' of undefined. I import like this: import xml_data from '../../xmldata/list.xml';
Thank you, your solution is also nice, but I need programmatically changeable file, in order to edit some data.
2

Try the below code.

import xmlData from '../../xmldata/list.xml';
import XMLParser from 'react-xml-parser';

var jsonDataFromXml = new XMLParser().parseFromString(xmlData);

list.xml

<?xml version='1.0' encoding='utf-8'?>
<?xml-stylesheet type="text/xsl" href="ACSPIXMT.xsl" ?>

<Library>
   <Books count='1'>
       <Book id='1'>
           <Name>Me Before You</Name>
           <Author>Jojo Moyes</Author>
       </Book>
   </Books>
   <Music count=1>
       <CD id='2'>
           <Name>Houses of the Holy</Name>
           <Artist>Led Zeppelin</Artist>
       </CD>
   </Music>
</Library>

Your data will be in 'jsonDataFromXml' variable.

Note:

If your data is inside the src directory, please use the appropriate path and uncomment 'Suggestion 2' otherwise, uncomment 'Suggestion 1' if your folder is parallel to src folder.

Better to check for data validity also in case if it not XML file all the time.

10 Comments

thx @nikhil-goyal, here returns me: TypeError: Cannot set property 'value' of undefined
How to check for data validity?
Can you please send me the complete error and the file where you are using the method?
I'm using the method inside of AdminScreen component, in order to get some data from xml. I sent complete error above*
Did you try checking the value in xmlData variable if it is coming or not?
|
1

You don't need to convert your xml to js

this is the solution that works for me

import React, { Component } from "react";
import XMLParser from "react-xml-parser";
import List from "../xml.xml";

class App extends Component {
  constructor(props) {
    super(props);
    this.handleSubmit = this.handleSubmit.bind(this);
    this.state = {};
  }

  handleSubmit(event) {
    event.preventDefault();

    const file = this.App.files[0];

    const reader = new FileReader();

    reader.readAsText(file);

    reader.onloadend = evt => {
      const readerData = evt.target.result;

      const parser = new DOMParser();
      const xml = parser.parseFromString(readerData, "text/xml");

      console.log(
        "data",
        new XMLSerializer().serializeToString(xml.documentElement)
      );
      var XMLParser = require("react-xml-parser");
      var NewXml = new XMLParser().parseFromString(
        new XMLSerializer().serializeToString(xml.documentElement)
      ); // Assume xmlText contains the example XML
      console.log("newxml", NewXml);

      this.setState({ xml });
    };
  }

  render() {
    return (
      <div className="App">
        <header className="App-header">
          <h1 className="App-title">Insulog</h1>
        </header>
        <p className="App-intro">
          Please Enter your insulog XML file at the button below
        </p>

        <form onSubmit={this.handleSubmit}>
          <label>
            Upload file:
            <input
              type="file"
              ref={input => {
                this.App = input;
              }}
            />
          </label>
          <br />
          <button type="submit">Submit</button>
        </form>

        <h2>XML Readings of ST_TIMERANGE and WEEKS: </h2>
      </div>
    );
  }
}
export default App;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.