XML (Extensible Markup Language) is a widely used format for structuring data that is both human-readable and machine-readable. XML parsing involves extracting meaningful information from an XML document. In Flutter, this is particularly useful when consuming data from XML-based APIs, configuration files, or other sources. This answer will walk us through parsing and displaying XML data in a Flutter application.
To begin parsing XML data, we must install the necessary package. For this purpose, we will open the pubspec.yaml in our Dart project and add the following line under the "dependencies" section:
dependencies:
flutter:
sdk: flutter
xml:
Leaving the version number empty will automatically install the latest version of the package.
After making the changes, we can install the package in two ways:
Right-click the pubspec.yaml
file and click on "get packages."
Write the following command in the terminal.
flutter pub get
We can skip all the above steps and just run the following command, which will automatically install the latest version of the xml
package.
flutter pub add xml
Now we can import the package into the Dart file by adding the following line of code in the Dart file where we want to parse and display XML data:
import 'package:flutter/material.dart';import 'package:xml/xml.dart' as xml;
We can parse the XML data by following the below steps:
_loadData
functionIn your main.dart
file, we can import the necessary packages, and define the XML parsing function:
// Function to load and parse XML datavoid _loadData() async {final temporaryList = [];// Code for parsing XML data.}
Within the _loadData()
function, we can define XML data. In real life, this is usually fetched from an API or an XML file. In this example, we use this XML document to simulate the API response:
// Simulate fetching XML data from an API or fileconst employeeXml = '''<?xml version="1.0"?><employees><employee><name>Spiderman</name><salary>5000</salary></employee><!-- More employee entries --></employees>''';
Within the _loadData()
function, we can parse XML data and extract employee information using a loop:
// Parse XML datafinal document = xml.XmlDocument.parse(employeeXml);final employeesNode = document.findElements('employees').first;final employees = employeesNode.findElements('employee');// Extract employee data using a loopfor (final employee in employees) {final name = employee.findElements('name').first.text;final salary = employee.findElements('salary').first.text;temporaryList.add({'name': name, 'salary': salary});}
Line 1: The xml.XmlDocument.parse(employeeXml)
method parses the XML string employeeXml
and creates an XmlDocument
object named document
.
Line 2: The findElements('employees')
method is called on the document
to locate all elements with the tag name 'employees.' Since there is only one 'employees' element, .first
is used to retrieve the first and only element with the tag 'employees'. This element is stored in the employeesNode
variable.
Line 3: Similarly, the findElements('employee')
method is called on employeesNode
to locate all elements with the tag name 'employee.' This returns a list of all 'employee' elements in the 'employees' node. The list is stored in the employees
variable.
Lines 5–9: A loop is used to iterate over each 'employee' element in the employees
list. For each 'employee' element, the findElements
method is used again to locate the 'name' and 'salary' elements within the 'employee' element. .first.text
retrieves the text content of the first occurrence of the respective element. The extracted 'name' and 'salary' values are then used to create a map entry representing an employee, which is added to the temporaryList
.
After the loop, the temporaryList
contains a list of maps, each representing an employee with their name and salary. This list then updates the UI and displays the parsed data.
To display parsed XML data, we can use Flutter widgets like the ListView.builder
:
ListView.builder(itemBuilder: (context, index) => Card(// ...child: ListTile(title: Text(_employees[index]['name']),subtitle: Text("Salary: \$${_employees[index]['salary']}"),),),itemCount: _employees.length,),
After running the above code, we can see the following output:
We get the following code by putting together the code explained above.
// main.dart import 'package:flutter/material.dart'; import 'package:xml/xml.dart' as xml; void main() { runApp( MyApp()); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( // Remove the debug banner debugShowCheckedModeBanner: false, title: 'Educative Answers', theme: ThemeData( primarySwatch: Colors.blue, ), home: HomeScreen(), ); } } class HomeScreen extends StatefulWidget { @override State<HomeScreen> createState() => _HomeScreenState(); } class _HomeScreenState extends State<HomeScreen> { // This list will be displayed in the ListView List _employees = []; // This function will be triggered when the app starts void _loadData() async { final temporaryList = []; // in real life, this is usually fetched from an API or from an XML file // In this example, we use this XML document to simulate the API response const employeeXml = '''<?xml version="1.0"?> <employees> <employee> <name>Spiderman</name> <salary>5000</salary> </employee> <employee> <name>Dr. Strange</name> <salary>6000</salary> </employee> <employee> <name>Thanos</name> <salary>7000</salary> </employee> <employee> <name>Iron Man</name> <salary>8000</salary> </employee> </employees>'''; // Parse XML data final document = xml.XmlDocument.parse(employeeXml); final employeesNode = document.findElements('employees').first; final employees = employeesNode.findElements('employee'); // loop through the document and extract values for (final employee in employees) { final name = employee.findElements('name').first.text; final salary = employee.findElements('salary').first.text; temporaryList.add({'name': name, 'salary': salary}); } // Update the UI setState(() { _employees = temporaryList; }); } // Call the _loadData() function when the app starts @override void initState() { super.initState(); _loadData(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text('Educative XML Answer')), body: Padding( padding: const EdgeInsets.symmetric(vertical: 20), // list of employees child: ListView.builder( itemBuilder: (context, index) => Card( key: ValueKey(_employees[index]['name']), margin: const EdgeInsets.symmetric(vertical: 5, horizontal: 15), color: Colors.amber.shade100, elevation: 4, child: ListTile( title: Text(_employees[index]['name']), subtitle: Text("Salary: \$${_employees[index]['salary']}"), ), ), itemCount: _employees.length, ), ), ); } }
In this Answer, we learned how to parse and display XML data in a Flutter application. We can seamlessly integrate XML data into our app's user interface using the xml
package and Flutter widgets. Refer to the official documentation of the xml
package and Flutter for more advanced features and customization options.
Free Resources