Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse xml file in react?

I have tried using some libraries but I can not seem to find any answer. i have a React site and I am uploading a file using a form. I'm looking for a way to parse the XML file, and reach it's children and I can't seem to find the way to do that.

My form:

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

my listener:

my event:

 handleSubmit(event) {

    //here the file will be opened
    //submit pressed


    var rawFile = new XMLHttpRequest();
    var allText;
    rawFile.open("GET", this.App.files[0], false);
    rawFile.onreadystatechange = function ()
    {
        if(rawFile.readyState === 4)
        {
            if(rawFile.status === 200 || rawFile.status == 0)
            {
                allText = rawFile.responseText;
                // alert(allText);
            }
        }
    }

    rawFile.send(null);
    alert(allText);
  }

my xml file:

<?xml version="1.0" encoding="ISO-8859-1" ?>
<?xml-stylesheet type="text/xsl" href="ACSPIXMT.xsl" ?>

<IMPORT>
<ACSPIX Type="2106" SN="UI00650521" Ver="3.05.01"/>
<DEVICE  Name="Performa" SN="04666273"  ModelNum="591" Dt="2018-04-17" Tm="13:53" BGUnit="mg/dL">
</DEVICE>
<RECENTREC Dt="2014-02-11" Tm="18:47"/>
<BGDATA>
<BG Val="226" Dt="2014-02-11" Tm="18:47" D="1"/>
<BG Val="149" Dt="2014-02-08" Tm="18:23" D="1"/>
<BG Val="101" Dt="2014-02-07" Tm="20:56" D="1"/>
<BG Val="275" Dt="2014-02-07" Tm="18:49" D="1"/>
<BG Val="301" Dt="2014-02-06" Tm="19:13" D="1"/>
<BG Val="112" Dt="2014-02-06" Tm="07:20" D="1"/>
<BG Val="213" Dt="2014-02-05" Tm="19:42" D="1"/>
<BG Val="111" Dt="2014-02-05" Tm="12:02" D="1"/>
<BG Val="212" Dt="2014-02-04" Tm="19:18" D="1"/>
</BGDATA>
<STATISTIC>
<ST_TIMERANGE Weeks="2" Dt="2014-02-11"/>
<ST_EVALRESULTS Val="9"/>
<ST_TSTFREQ1 Val="0.6"/>
<ST_TSTFREQ2 Val="1.5"/>
<ST_MBG Val="189"/>
<ST_SD Val=" 74"/>
<ST_HBGI Val="12.3"/>
<ST_LBGI Val="0.0"/>
</STATISTIC>
<CHECK CRC="4816"/>
</IMPORT>

I'm trying to reach one of the fields in the XML. Can anyone help me with the importing the file and reaching the fields?

Thank you.

like image 524
Chief Madog Avatar asked May 21 '18 06:05

Chief Madog


2 Answers

You can use DOMParser to convert the XML to DOM.

const rawFile = new XMLHttpRequest();

rawFile.onreadystatechange = () => {
  if (rawFile.readyState === 4 && (rawFile.status === 200 || rawFile.status === 0)) {
    const parser = new DOMParser();
    const xml = parser.parseFromString(rawFile.response, 'text/xml');

    // Do your querying here.
    // xml will can now be queried like DOM
    // e.g. xml.querySelector('ST_TIMERANGE').getAttribute('Weeks') // returns 2.
  }
};

rawFile.open('GET', this.App.files[0], false);
rawFile.send();

const raw = `<?xml version="1.0" encoding="ISO-8859-1" ?>
  <?xml-stylesheet type="text/xsl" href="ACSPIXMT.xsl" ?>

  <IMPORT>
  <ACSPIX Type="2106" SN="UI00650521" Ver="3.05.01"/>
  <DEVICE  Name="Performa" SN="04666273"  ModelNum="591" Dt="2018-04-17" Tm="13:53" BGUnit="mg/dL">
  </DEVICE>
  <RECENTREC Dt="2014-02-11" Tm="18:47"/>
  <BGDATA>
  <BG Val="226" Dt="2014-02-11" Tm="18:47" D="1"/>
  <BG Val="149" Dt="2014-02-08" Tm="18:23" D="1"/>
  <BG Val="101" Dt="2014-02-07" Tm="20:56" D="1"/>
  <BG Val="275" Dt="2014-02-07" Tm="18:49" D="1"/>
  <BG Val="301" Dt="2014-02-06" Tm="19:13" D="1"/>
  <BG Val="112" Dt="2014-02-06" Tm="07:20" D="1"/>
  <BG Val="213" Dt="2014-02-05" Tm="19:42" D="1"/>
  <BG Val="111" Dt="2014-02-05" Tm="12:02" D="1"/>
  <BG Val="212" Dt="2014-02-04" Tm="19:18" D="1"/>
  </BGDATA>
  <STATISTIC>
  <ST_TIMERANGE Weeks="2" Dt="2014-02-11"/>
  <ST_EVALRESULTS Val="9"/>
  <ST_TSTFREQ1 Val="0.6"/>
  <ST_TSTFREQ2 Val="1.5"/>
  <ST_MBG Val="189"/>
  <ST_SD Val=" 74"/>
  <ST_HBGI Val="12.3"/>
  <ST_LBGI Val="0.0"/>
  </STATISTIC>
  <CHECK CRC="4816"/>
  </IMPORT>`;
const parser = new DOMParser();
const xml = parser.parseFromString(raw, 'text/xml');

console.log(xml.querySelector('ST_TIMERANGE').getAttribute('Weeks'));
like image 104
dork Avatar answered Sep 20 '22 17:09

dork


Here is a working example with xml2js :

• You can use the fetch api to pull data from a .XML file like this:

• responseText is the .XML datasource fetched from example.xml

• within the curly braces of .then((responseText) = {}) the xml2json script is added to parse the .xml data to Json format console.log(result) will render the json format in the terminal essentially transforming console.log(responseText) XML to console.log(result) JSON you can use state to structure your data as you would with any json data file.

side note : if you remove the parse string and add console.log(responseText) instead the output will be in XML format in your terminal for comparison.

 import React, {Component} from 'react';
 import {parseString} from 'xml2js'



    class App extends Component {


     componentDidMount(){
      this._isMounted = true;
      var url = "https://example.xml"
      fetch(url)
        .then((response) => response.text())
        .then((responseText) => {
       parseString(responseText, function (err, result) {
         console.log(result);
         return result;
        });
      this.setState({
        datasource : result
        })
       })
    .catch((error) => {
      console.log('Error fetching the feed: ', error);
    });
  }



      componentWillUnMount() {
         this._isMounted = false;
      }
      
      

      render(){
        return(
          <div>

          </div>

        )
      }
    }

    export default App;
like image 35
Ali Shirazee Avatar answered Sep 18 '22 17:09

Ali Shirazee