【问题标题】:XMLParser giving error ''Cannot set property value of undefined''XMLParser 给出错误“无法设置未定义的属性值”
【发布时间】:2017-07-28 05:41:53
【问题描述】:

我在 React Native App 中工作,只是尝试执行这段代码

fetch('https://ad13.adfarm1.adition.com/banner?sid=3915124&wpt=X.xml')
.then((response) => response.text())
.then((responseJson) => {
    console.log("WorkingTillHere",responseJson)
    xml_Img = new XMLParser().parseFromString(responseJson);    // Assume xmlText contains the example XML
    console.log("ParserVideo,",xml_Img);
}) .catch((error) => {
    console.log("ParserEx",error);
});

我可以在控制台窗口中看到

在这里工作

但它没有执行 XMLParser().parseFromString(responseJson); 并且正在获取控制台日志

ParserEx TypeError: 无法设置未定义的属性“值”

同样的代码在这个 URL 链接 fetch('http://teststream.airtango.de/theo/vast.xml') 上工作得很好

【问题讨论】:

  • 我认为你应该调用一个异步来从http请求中获取数据,尝试添加“await fetch”并在你的函数前面添加异步
  • @GaneshCauda - 为什么? .then 链在适当的时候被调用
  • 我可以在原始 XML 中看到的唯一区别是它工作的位置 <![CDATA[]]> 在各自的行中 - 而在失败的数据中你在一行中有<Error><![CDATA[ ... blah blah blah ...]]></Error> - XMLParser 是什么?是this one吗?
  • 所有的链都会被调用,但是如果你不使用异步,你的响应中将没有数据。您可以尝试使用几种方法来处理异步函数,使用 async/await、promise 或回调,但如果想要一个简单的方法,只需使用 async 和 await。你可以在这里找到如何写它:facebook.github.io/react-native/docs/network.html
  • 不...是<?xml version="1.0" encoding="UTF-8"?>抛出它

标签: javascript xml react-native xml-parsing


【解决方案1】:

react-xml-parser 看不懂

<?xml version="1.0" encoding="UTF-8"?>

标题。所以,一般来说,你可以

fetch('https://ad13.adfarm1.adition.com/banner?sid=3915124&wpt=X.xml')
.then((response) => response.text())
.then((xmlText) => {
    // remove <?xml  ... etc header because react-xml-parser chokes on it
    if (xmlText.toLowerCase().substr(0,5) == '<?xml') {
        xmlText = xmlText.split(/\?>\r{0,1}\n{0,1}/).slice(1).join('?>\n');
    }
    console.log("WorkingTillHere",xmlText)
    xml_Img = new XMLParser().parseFromString(xmlText);    // Assume xmlText contains the example XML
    console.log("ParserVideo,",xml_Img);
}) .catch((error) => {
    console.log("ParserEx",error);
});

只有前 5 个字符是 &lt;?xml 时,上述内容才会捕捉到它……这对我来说可能有点幼稚。但是,我相信react-xml-parser 的作者应该在他们的代码中处理&lt;?xml ... ?&gt;:p

查看 xmlParser 的源代码,似乎他们确实尝试处理它,但显然失败了

注意,将 xmlParse.js 的第 8 行从

if (tags[i].indexOf('?xml')) {

if (tags[i].indexOf('?xml') < 0 && tags[i].length > 0) {

也解决了这个问题:p

【讨论】:

  • 不幸的是它没有工作....your CodeOutput is here
  • 其实,试试我刚刚更新的代码的细微变化
  • @RaihanAbbas - 再次更新代码以更宽容不同类型的“行尾”
  • 我的错...它实际上工作...Idk不知何故控制台窗口没有更新...请忽略上面的评论..我已经上传了您的代码输出的更新屏幕截图here .. .apologies @Jaromanda X
猜你喜欢
  • 2017-04-26
  • 1970-01-01
  • 2019-10-14
  • 2022-01-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-09
  • 1970-01-01
相关资源
最近更新 更多