简体   繁体   English

如何在反应中解析xml文件?

[英]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.我有一个 React 站点,我正在使用表单上传文件。 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.我正在寻找一种解析XML文件的方法,并找到它的孩子,但我似乎找不到这样做的方法。

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 文件:

<?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.我正在尝试访问 XML 中的字段之一。 Can anyone help me with the importing the file and reaching the fields?任何人都可以帮助我导入文件并到达字段吗?

Thank you.谢谢你。

You can use DOMParser to convert the XML to DOM.您可以使用DOMParser将 XML 转换为 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'));

Here is a working example with xml2js :这是一个使用 xml2js 的工作示例:

• You can use the fetch api to pull data from a .XML file like this: • 您可以使用 fetch api 从 .XML 文件中提取数据,如下所示:

• responseText is the .XML datasource fetched from example.xml • responseText 是从 example.xml 获取的 .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. • 在 .then((responseText) = {}) 的大括号内,添加 xml2json 脚本以将 .xml 数据解析为 Json 格式 console.log(result) 将在终端中呈现 json 格式,本质上是将 console.log( responseText) XML 到 console.log(result) JSON 您可以像处理任何 json 数据文件一样使用 state 来构建数据。

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.旁注:如果删除解析字符串并添加 console.log(responseText) ,则终端中的输出将采用 XML 格式以进行比较。

 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;

You can use childNodes , getElementsByTagName , etc on it the way you could an html document.您可以像使用 html 文档一样在其上使用childNodesgetElementsByTagName等。

You can see an example of parsing XML with javascript here: https://www.w3schools.com/xml/xml_parser.asp您可以在此处查看使用 javascript 解析 XML 的示例: https : //www.w3schools.com/xml/xml_parser.asp

If you tell me what node you are trying to access on that document I can try to help you further.如果您告诉我您尝试访问该文档的哪个节点,我可以尝试进一步帮助您。

The easiest method is to use an npm package to convert xml to json and use like an object.最简单的方法是使用npm包将xml转换成json,像对象一样使用。 You can use this, xml2json npm module你可以使用这个, xml2json npm 模块

var parser = require('xml2json');

var xml = "<foo attr=\"value\">bar</foo>";
console.log("input -> %s", xml)

// xml to json
var json = parser.toJson(xml);
console.log("to json -> %s", json);

// json to xml
var xml = parser.toXml(json);
console.log("back to xml -> %s", xml)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM