blowonthepi
blowonthepi

Reputation: 81

How to get text value from XML in Flutter

I would like to know how to get the text value from an XML document in flutter. I know to use the XML dart library already just having trouble when it comes to parsing the variables. For example: The XML line: Bob In my current parsing set up returns: (Bob) How do I do it without the brackets?

Upvotes: 1

Views: 7940

Answers (1)

blowonthepi
blowonthepi

Reputation: 81

UPDATE:

Instead of converting XML to JSON you can use the Flutter XML package (https://pub.dev/packages/xml)

Example:

XmlDocument xml = XmlDocument.parse('''
<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<Results>
    <Person>
        <Name>Joe Blogs</Name>
        <Age>21</Age>
    </Person>
    <Person>
        <Name>Alexander Hamilton</Name>
        <Age>28</Age>
    </Person>
</Results>
''');

print(xml.getElement("Results")
    .firstElementChild.getElement("Person").getElement("Name").text);
print(xml.getElement("Results")
    .firstElementChild.getElement("Person").getElement("Age").text);

Output:

Joe Blogs
21

I would recommend this updated method as converting to JSON can incorrectly parse causing data loss.


OLD VERSION:

I managed to get around my issue with inspiration from @CopsOnRoad.

I parsed the XML data returned from the API to a JSON array using the Flutter package: https://pub.dev/packages/xml2json

And then managed to display it with arrays.

Example:

String xmlString = '''
<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<!DOCTYPE root SYSTEM "rootDtd" "dtd/root.dtd">
<root>
    <element1>Child 1</element1>
    <element2>Child 2</element2>
    <element3>Child 3</element3>
    <element4>Child 4</element4>
    <element5>Child 5</element5>
    <element6>Child 6</element6>
    <element7>Child 6</element7>
</root>
''';
          Xml2Json xml2json = new Xml2Json();

          xml2json.parse(xmlString);
          var json = xml2json
              .toParker(); // the only method that worked for my XML type.

          print(json);
          var response = jsonDecode(json);
          print(response);
        } catch (JSONException) {}

Upvotes: 6

Related Questions