You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React-Native使用fast-xml-parser解析XML遇TypeError错误求助

问题:React-Native中使用fast-xml-parser v3.20.0解析XML时出现TypeError: parse is not a function

在React-Native项目中使用fast-xml-parser v3.20.0解析XML并打印数据时,触发未处理的Promise拒绝错误,提示TypeError: (0, _fastXmlParser.parse) is not a function,即parse方法未定义。

提供的代码及响应

前端代码

import { parse } from 'fast-xml-parser';

function test(){
  const emp_number = 20209;
  fetch('http://website.com/partner/api.php?emp_number='+`${emp_number}`, {
  method: 'POST',
  headers: {
    Accept: 'text/plain',
    'Content-Type': 'text/plain'
  }
})
  .then((response) => response.text())
  .then((data) => {
            let obj = parse(data);
            let servicenumber = obj.counter.serviceNumber;
            let consumpationtype = obj.counter.consumpationtype;
            let currentread = obj.counter.currentread;
            let currentdate = obj.counter.currentdate;
            let lastread = obj.counter.lastread;
            let lastdate = obj.counter.lastdate;
            let consumpation = obj.counter.consumpation;
            console.log("CurrentReading:"+`${currentread}`);
});}

后端api.php代码

<?php
    header('Content-Type: text/plain');
    $gecolEmployee = $_GET['emp_number'];

    $serverName = "host\SqlS";
    $connectionInfo = array( "Database"=>"gecol");
    $conn = sqlsrv_connect( $serverName, $connectionInfo);
        $query = "SELECT * FROM readers WHERE emp_number=?";
        $result = sqlsrv_query($conn, $query, array($gecolEmployee));
        $row = sqlsrv_fetch_array($result);
        if( $conn ) {
            echo $row['xml'];
        }else{
            echo "خطأ.<br />";
            die( print_r( sqlsrv_errors(), true));
        }
?>

XML响应

<counter>
    <serviceNumber>200135644</serviceNumber>
    <consumpationtype>1</consumpationtype>
    <currentread>95808</currentread>
    <currentdate>29/6/2022</currentdate>
    <lastread>85808</lastread>
    <lastdate>29/5/2022</lastdate>
    <consumpation>?</consumpation>
    <counternumber>7038842</counternumber>
    <phonenumber>0928065968</phonenumber>
</counter>

解决方案

1. 修正fast-xml-parser的导入方式

v3.x版本的fast-xml-parser默认导出是一个对象,并非直接导出parse方法,两种正确导入方式:

  • 方式一:导入默认对象后调用parse方法
import xmlParser from 'fast-xml-parser';

// 使用时
let obj = xmlParser.parse(data);
  • 方式二:从指定路径导入命名的parse方法
import { parse } from 'fast-xml-parser/src/parser';

2. 可选:添加解析配置(优化解析行为)

可传入配置参数确保解析结果符合预期,比如自动去除字符串首尾空格:

const parseOptions = {
  trimValues: true,
  ignoreAttributes: false
};
let obj = xmlParser.parse(data, parseOptions);

3. 添加错误捕获(避免未处理的Promise拒绝)

在fetch链式调用中加入catch块,捕获请求或解析过程中的错误:

fetch(/* 请求配置 */)
.then(/* 响应处理 */)
.then(/* 解析逻辑 */)
.catch(error => {
  console.error('处理出错:', error);
});

修改后的完整前端代码示例

import xmlParser from 'fast-xml-parser';

function test(){
  const emp_number = 20209;
  fetch('http://website.com/partner/api.php?emp_number='+`${emp_number}`, {
    method: 'POST',
    headers: {
      Accept: 'text/plain',
      'Content-Type': 'text/plain'
    }
  })
  .then((response) => response.text())
  .then((data) => {
    const parseOptions = { trimValues: true };
    let obj = xmlParser.parse(data, parseOptions);
    let servicenumber = obj.counter.serviceNumber;
    let consumpationtype = obj.counter.consumpationtype;
    let currentread = obj.counter.currentread;
    let currentdate = obj.counter.currentdate;
    let lastread = obj.counter.lastread;
    let lastdate = obj.counter.lastdate;
    let consumpation = obj.counter.consumpation;
    console.log("CurrentReading:"+`${currentread}`);
  })
  .catch((error) => {
    console.error('处理出错:', error);
  });
}

内容的提问来源于stack exchange,提问作者MrObscure

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 10:35:24