如何在 Flutter 中解析和渲染 XML 数据

这篇简洁的文章向您展示了如何在 Flutter 中解析和显示 XML 数据。

概述

与 JSON 一样,XML 可用于从 Web 服务器接收数据。然而,JSON 是一种数据交换格式,只提供数据编码规范,而 XML 是一种使用严格语义来指定自定义标记语言的语言,提供的功能远不止数据交换。

一般来说,JSON 更快更容易使用。尽管如此,XML 更强大,并且可以降低具有纯粹数据结构要求的大型应用程序中的软件风险。

要在 Flutter 中使用 XML,我们需要完成以下步骤:

  • 获取 XML 文档
  • 使用 XML DOM 循环遍历文档
  • 提取值并将它们存储在变量中

一个名为xml的包可以帮助我们在处理 XML 数据时节省时间和精力。让我们构建一个完整的示例应用程序以获得更好的理解。

例子

我们要建造什么?

这个演示呈现了一个虚构公司的员工列表,包括他们的姓名和薪水。信息以 XML 格式提供(在现实生活中,此类数据通常从 API 或文件中获取):

<?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>
      <employee>
        <name>KindaCode.com</name>
        <salary>0.5</salary>
      </employee>
</employees>

应用截图:

如何在 Flutter 中解析和渲染 XML 数据

代码

  1. 通过运行以下命令安装软件包:
flutter pub add xml

然后执行这个:

flutter pub get
  1. main.dart 中的完整源代码(附解释):
// main.dart
import 'package:flutter/material.dart';
import 'package:xml/xml.dart' as xml;

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      // Remove the debug banner
      debugShowCheckedModeBanner: false,
      title: 'KindaCode.com',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const HomeScreen(),
    );
  }
}

class HomeScreen extends StatefulWidget {
  const HomeScreen({Key? key}) : super(key: key);

  @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>
      <employee>
        <name>KindaCode.com</name>
        <salary>0.5</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('KindaCode.com')),
      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,
        ),
      ),
    );
  }
}

最后的话

您已经学习了如何解析和提取 XML 文档中的值以显示在列表视图中。如果您愿意,可以修改代码以改进应用程序。