Home > Net >  how xml parsing in flutter
how xml parsing in flutter

Time:07-11

i wanna parse xml in flutter. but when i used xml libariy, i can not get value in <>? how can i get the value of element tag ?

i wanna get the value like this {'plant':[NBJF,CCJF,CQBF,....] } just like json

This is the xml:

<?xml version="1.0" encoding="UTF-8" standalone="no"?><SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"><SOAP-ENV:Body><fjs1:GetPlantResponse xmlns:fjs1="http://www.dsc.com.tw/tiptop/TIPTOPServiceGateWay"><fjs1:response><Response>
  <Execution>
    <Status code="0" sqlcode="0" description=""/>
  </Execution>
  <ResponseContent>
    <Parameter>
      <Record>
        <Field name="defaultplant" value="NBJF"/>
      </Record>
    </Parameter>
    <Document>
      <RecordSet id="1">
        <Master name="Master">
          <Record>
            <Field name="plant" value="CCJF"/>
          </Record>
        </Master>
      </RecordSet>
      <RecordSet id="2">
        <Master name="Master">
          <Record>
            <Field name="plant" value="CDJF"/>
          </Record>
        </Master>
      </RecordSet>
    </Document>
  </ResponseContent>
</Response>
</fjs1:response>
</fjs1:GetPlantResponse>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>

this is my code:

import 'package:xml/xml.dart' as xml;
import 'package:http/http.dart' as http;

void main() async {
  String url = "http://erp.nb-jf.com/web/ws/r/aws_ttsrv2?wsdl";

  String xmlReq = '''  
                ''';

  http.Response response = await http.post(
      Uri.parse("http://erp.nb-jf.com/web/ws/r/aws_ttsrv2?wsdl"),
      headers: {
        'Content-Type': "text/xml; charset=UTF-8",
        'SOAPAction': "\"\"",
      },
      body: '$xmlReq');

  var rawXmlResponse = response.body;
  xmlReq = rawXmlResponse.replaceAll('&lt;', '<');
  xmlReq = xmlReq.replaceAll('&gt;', '>');

  List itemList = [];

  xml.XmlDocument xmlText = xml.XmlDocument.parse(xmlReq);
  var elements = xmlText.findAllElements("Record");

  elements.forEach((element) {
    print(element.findElements("Field"));
    
  });
}

i do not know how to get the value in tag.

CodePudding user response:

You have two ways to do this task

  1. use xml: ^6.1.0 package and parse XML response.
  2. Or user xml2json: ^5.3.3 package to covert your XML response to json and use it.

CodePudding user response:

Just use xml: ^6.1.0

import 'package:xml/xml.dart';

final bookshelfXml = '''<?xml version="1.0"?>
    <bookshelf>
      <book>
        <title lang="en">Growing a Language</title>
        <price>29.99</price>
      </book>
      <book>
        <title lang="en">Learning XML</title>
        <price>39.95</price>
      </book>
      <price>132.00</price>
    </bookshelf>''';
final document = XmlDocument.parse(bookshelfXml);
  • Related