我尝试读取xml文件,并使用react-xml-parser
库进行解析。
var XMLParser = require('react-xml-parser');
var xml = new XMLParser().parseFromString(xml_string);
console.log(xml);
console.log(xml.getElementsByTagName('Row'));
这里,它应该从字符串中读取,但是我需要从文件中获取它。我的xml文件位于目录xmldata/list.xml
中,所以我现在不怎么做。
尝试此代码:
import XMLData from './xmldata/list.xml';
function ReadData() {
var jsonDataFromXml = new XMLParser().parseFromString(XMLData);
console.log(jsonDataFromXml);
console.log(jsonDataFromXml.getElementsByTagName('Row'));
}
}
}
但结果是:
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
尝试导入文件,并在如下所示的解析器中使用它。
Import xml_data from 'path of your xml file';
var xml = new XMLParser().parseFromString(xml_data);
希望这会对您有所帮助。如果您有任何问题,请告诉我。
尝试下面的代码。
// import xmlData from '/xmldata/list.xml'; // Suggestion 1
// import xmlData from 'xmldata/list.xml'; // Suggestion 2
import XMLParser from 'react-xml-parser';
var jsonDataFromXml = new XMLParser().parseFromString(xmlData);
您的数据将在'jsonDataFromXml'变量中。
注意:
如果您的数据位于src目录中,请使用适当的路径,并取消注释'Suggestion 2',否则,如果文件夹与src文件夹平行,则取消注释'Suggestion 1'。
最好检查数据有效性,以防它始终不是XML文件。