您可以考虑miniML-Parser,这是一个简单而小巧的 C 语言 XML 解析器库。
- 与其他 XML 解析器不同,它非常易于使用。您只需调用一个 API 即可解析您的 XML 数据。
- 它是一个验证解析器。它验证 XML 数据的语法并提取 XML 数据的内容。
为了从 XML 数据中解析和提取内容,您需要向解析器提供一些信息。例如 XML 元素名称、其子元素、属性、内容类型等。解析器使用 xs_element_t 结构来保存 XML 数据的所有这些属性
在您的示例中,您有 2 个 XML 元素“用户”和“参数”。 user 是根元素,param 是子元素。属性“名称”和“值”保存内容。为了提取这些内容,您需要指定内容类型和目标地址来存储内容。
您的 XML 数据的 xs_element_t 示例。
const xs_element_t user_root =
{
.Name.String = "user", //!< name of XML element
.Name.Length = 4, //!< Length of name
.Attribute_Quantity = 1, //!< Number of attributes of this element
.Attribute = attributes, //!< Address of structure containing attributes
.Child_Quantity = 1, //!< Number of child elements
.Child = ¶m_element, //!< Address of structure holding child elements
};
const xs_element_t param_element =
{
.Name.String = "param", //!< name of XML element
.Name.Length = 5, //!< Length of name
.Attribute_Quantity = 2, //!< Number of attributes of this element
.Attribute = attributes, //!< Address of structure containing attributes
};
//! Holds properties of attributes
const xs_attribute_t attributes[] =
{
[0].Name.String = "name", //!< Name of XML attribute
[0].Name.Length = 4, //!< Length of attribute name
[0].Target.Type = EN_STATIC, //!< Target address type is static.
[0].Target.Address = &name, //!< Target address offset from the parent target address
[0].Content.Type = EN_STRING, //!< Content type is string.
[1].Name.String = "value", //!< Name of XML attribute
[1].Name.Length = 4, //!< Length of attribute name
[1].Target.Type = EN_STATIC, //!< Target address type is static.
[1].Target.Address = &value, //!< Target address offset from the parent target address
[1].Content.Type = EN_STRING, //!< Content type is string.
};
注意:以上结构不完整。为了使示例简单,我省略了一些结构成员。
要解析 xml 数据,然后调用 parse_xml() 并传递 user_root(根元素)的地址和 XML 数据。
parse_xml(&user_root, xml_data, NULL);
您还可以在 xs_element_t 结构中注册一个回调函数,以便在解析器在解析过程中遇到元素/标签时获取回调。
更多详情请参考https://github.com/kiishor/miniML-Parser
披露:我是这个 miniML-Parser 的作者