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

React Native中如何从SOAP响应获取emailEntidade和telEntidade字段

How to Extract emailEntidade and telEntidade from a SOAP Response in React Native

Hey there! Let's work through this SOAP response parsing issue you're hitting in React Native. The main problem here is handling namespace-prefixed keys (like SOAP-Env:Envelope) correctly in JavaScript, plus making sure you're properly parsing the response if it's XML. Here's a step-by-step solution:

1. The Key Fix: Bracket Notation for Namespace Keys

JavaScript doesn't allow dot notation for keys containing colons or special characters. So instead of trying response.SOAP-Env:Envelope, you need to use bracket notation like response['SOAP-Env:Envelope'] to access these properties. That's the first common pitfall you might have run into!

2. Parse XML Responses (React Native Needs a Helper Library)

Most SOAP APIs return XML, and React Native doesn't include a built-in XML parser like browsers do. You'll need a third-party library like react-native-xml2js to convert the XML string into a workable JavaScript object.

First, install the library:

npm install react-native-xml2js
# or
yarn add react-native-xml2js

3. Full Implementation Code

Here's a complete example using fetch and react-native-xml2js to extract your target properties:

import { parseString } from 'react-native-xml2js';

const fetchAndExtractData = async () => {
  try {
    // Fetch the SOAP response
    const response = await fetch('http://myjson.com/14veid', {
      method: 'GET',
      headers: {
        'Accept': 'text/xml', // Match your API's expected content type
      },
    });

    // Convert the response to an XML string
    const xmlString = await response.text();

    // Parse XML into a JavaScript object
    parseString(xmlString, (parseError, parsedResult) => {
      if (parseError) {
        console.error('Failed to parse XML:', parseError);
        return;
      }

      // Critical debug step: Print the full parsed structure to map the hierarchy
      console.log('Full parsed data:', JSON.stringify(parsedResult, null, 2));

      // Access namespace keys with bracket notation
      const envelope = parsedResult['SOAP-Env:Envelope'];
      const body = envelope['SOAP-Env:Body'][0]; // xml2js wraps most nodes in arrays

      // Replace `YourResponseNode` with the actual node containing your target properties
      const targetData = body.YourResponseNode[0];
      
      // Extract the properties you need
      const emailEntidade = targetData.emailEntidade[0];
      const telEntidade = targetData.telEntidade[0];

      console.log('Extracted Email:', emailEntidade);
      console.log('Extracted Phone:', telEntidade);
    });
  } catch (fetchError) {
    console.error('Fetch failed:', fetchError);
  }
};

// Call the function wherever you need it (e.g., in a useEffect hook)
fetchAndExtractData();

4. Debugging Hack for React Native

Since deep debugging is tricky in React Native, add this line right after parsing to print the full structure of your data:

console.log('Full parsed structure:', JSON.stringify(parsedResult, null, 2));

This will show you exactly how the XML maps to JavaScript objects, so you can adjust the code to match the actual hierarchy leading to emailEntidade and telEntidade.

5. If Your Response is JSON (Not XML)

If your API returns a JSON object with namespace-prefixed keys, the solution is even simpler—just stick to bracket notation for the namespace keys:

const fetchAndExtractJson = async () => {
  try {
    const response = await fetch('http://myjson.com/14veid');
    const data = await response.json();

    // Access namespace keys with bracket notation
    const envelope = data['SOAP-Env:Envelope'];
    const targetData = envelope['SOAP-Env:Body'].yourResponseData;

    const email = targetData.emailEntidade;
    const phone = targetData.telEntidade;

    console.log('Email:', email);
    console.log('Phone:', phone);
  } catch (error) {
    console.error('Error:', error);
  }
};

The core fix here is always using bracket notation for keys with colons. Once you map the correct hierarchy from the debug log, extracting your target properties will be smooth sailing!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 06:57:13