We use essential cookies for the website to function, as well as analytics cookies for analyzing and creating statistics of the website performance. To agree to the use of analytics cookies, click "Accept All". You can manage your preferences at any time by clicking "Cookie Settings" on the footer. More Information.

Only Essential Cookies
Accept All

XML Parsing

When using XML as a data carrier, it is necessary to parse relevant elements in practice. This typically includes three types of operations: parsing XML tags and their values, parsing XML attributes and their values, and parsing XML event types and element information. For example, in web services, XML is the foundation of the Simple Object Access Protocol (SOAP). SOAP messages, which are usually encapsulated in XML format and contain request and response parameters, are parsed by web services to process client requests and generate corresponding responses.

The XML module provides the XmlPullParser class to parse XML text. The input is an ArrayBuffer or DataView that contains XML data, and the output is a structured parsing result.

Table 1 XML parsing options (see ParseOptions for detailed descriptions)

Expand
Name Type Mandatory Description
supportDoctype boolean No Whether to parse the document type. The value true means to parse the document type, and false means the opposite. The default value is false.
ignoreNameSpace boolean No Whether to ignore the namespace. If the namespace is ignored, it will not be parsed. The value true means to ignore the namespace, and false means the opposite. The default value is false.
tagValueCallbackFunction (name: string, value: string) => boolean No Callback used to return tagValue, which consists of XML tags and tag values. The default value is undefined, indicating that XML tags and their values are not parsed.
attributeValueCallbackFunction (name: string, value: string) => boolean No Callback used to return attributeValue, which consists of an attribute and its value. The default value is undefined, indicating that XML attributes and their values are not parsed.
tokenValueCallbackFunction (eventType: EventType, value: ParseInfo) => boolean No Callback used to return tokenValue, which consists of the XML event type and the attributes of parseInfo. The default value is undefined, indicating that the XML event type is not parsed.

Precautions

  • The input XML data must be in the standard format.

  • Parsing a specified node is not supported.

Parsing XML Tags and Values

  1. Import the module.

    Collapse
    Word wrap
    Dark theme
    Copy code
    1. import { xml, util } from '@kit.ArkTS'; // Use the API provided by the util module to encode text.
  2. Create an XmlPullParser object.

    You can create an XmlPullParser object based on ArrayBuffer or DataView. Both methods yield the same results.

    Collapse
    Word wrap
    Dark theme
    Copy code
    1. let strXml: string =
    2. '<?xml version="1.0" encoding="utf-8"?>' +
    3. '<note importance="high" logged="true">' +
    4. '<title>Play</title>' +
    5. '<lens>Work</lens>' +
    6. '</note>';
    7. let textEncoder: util.TextEncoder = new util.TextEncoder();
    8. let arrBuffer: Uint8Array = textEncoder.encodeInto(strXml); // Encode data to prevent garbled Chinese characters.
    9. // Method 1: Create an XmlPullParser object based on ArrayBuffer.
    10. let xmlParser: xml.XmlPullParser = new xml.XmlPullParser(arrBuffer.buffer as object as ArrayBuffer, 'UTF-8');
    Collapse
    Word wrap
    Dark theme
    Copy code
    1. // Method 2: Create an XmlPullParser object based on DataView.
    2. let dataView: DataView = new DataView(arrBuffer.buffer as object as ArrayBuffer);
    3. let xmlParser: xml.XmlPullParser = new xml.XmlPullParser(dataView, 'UTF-8');
  3. Customize a callback function. In this example, the callback function directly prints the tags and their values.

    Collapse
    Word wrap
    Dark theme
    Copy code
    1. function func(name: string, value: string): boolean {
    2. if (name == 'note') {
    3. console.info(name);
    4. }
    5. if (value == 'Play' || value == 'Work') {
    6. console.info(' ' + value);
    7. // ...
    8. }
    9. if (name == 'title' || name == 'lens') {
    10. console.info(' ' + name);
    11. }
    12. return true; // The value true means to continue parsing, and false means to stop parsing.
    13. }
  4. Set parsing options and call the parseXml function.

    Collapse
    Word wrap
    Dark theme
    Copy code
    1. let options: xml.ParseOptions = {supportDoctype:true, ignoreNameSpace:true, tagValueCallbackFunction:func};
    2. xmlParser.parseXml(options);

    The output is as follows:

    Collapse
    Word wrap
    Dark theme
    Copy code
    1. note
    2. title
    3. Play
    4. title
    5. lens
    6. Work
    7. lens
    8. note

Parsing XML Attributes and Values

  1. Import the module.

    Collapse
    Word wrap
    Dark theme
    Copy code
    1. import { xml, util } from '@kit.ArkTS'; // Use the util module to encode text.
  2. Create an XmlPullParser object.

    Collapse
    Word wrap
    Dark theme
    Copy code
    1. let strXml: string =
    2. '<?xml version="1.0" encoding="utf-8"?>' +
    3. '<note importance="high" logged="true">' +
    4. ' <title>Play</title>' +
    5. ' <title>Happy</title>' +
    6. ' <lens>Work</lens>' +
    7. '</note>';
    8. let textEncoder: util.TextEncoder = new util.TextEncoder();
    9. let arrBuffer: Uint8Array = textEncoder.encodeInto(strXml); // Encode data to prevent garbled Chinese characters.
    10. let xmlParser: xml.XmlPullParser = new xml.XmlPullParser(arrBuffer.buffer as object as ArrayBuffer, 'UTF-8');
  3. Customize a callback function. In this example, the callback function directly prints the attributes and their values.

    Collapse
    Word wrap
    Dark theme
    Copy code
    1. let str: string = '';
    2. function func(name: string, value: string): boolean {
    3. str += name + ' ' + value + ' ';
    4. return true; // The value true means to continue parsing, and false means to stop parsing.
    5. }
  4. Set parsing options and call the parseXml function.

    Collapse
    Word wrap
    Dark theme
    Copy code
    1. let options: xml.ParseOptions = {supportDoctype:true, ignoreNameSpace:true, attributeValueCallbackFunction:func};
    2. xmlParser.parseXml(options);
    3. console.info(str); // Print all attributes and their values.

    The output is as follows:

    Collapse
    Word wrap
    Dark theme
    Copy code
    1. importance high logged true // Attributes and values of the note node

Parsing XML Event Types and Element Information

  1. Import the module.

    Collapse
    Word wrap
    Dark theme
    Copy code
    1. import { xml, util } from '@kit.ArkTS'; // Use the util module to encode text.
  2. Create an XmlPullParser object.

    Collapse
    Word wrap
    Dark theme
    Copy code
    1. let strXml: string =
    2. '<?xml version="1.0" encoding="utf-8"?>' +
    3. '<note importance="high" logged="true">' +
    4. '<title>Play</title>' +
    5. '</note>';
    6. let textEncoder: util.TextEncoder = new util.TextEncoder();
    7. let arrBuffer: Uint8Array = textEncoder.encodeInto(strXml); // Encode data to prevent garbled Chinese characters.
    8. let xmlParser: xml.XmlPullParser = new xml.XmlPullParser(arrBuffer.buffer as object as ArrayBuffer, 'UTF-8');
  3. Customize a callback function. In this example, the callback function directly prints the event types and element depths.

    Collapse
    Word wrap
    Dark theme
    Copy code
    1. let str: string = '';
    2. function func(name: xml.EventType, value: xml.ParseInfo): boolean {
    3. str = name + ' ' + value.getDepth(); // Obtain the current depth of an element in the XML document.
    4. console.info(str);
    5. // ...
    6. return true; // The value true means to continue parsing, and false means to stop parsing.
    7. }
  4. Set parsing options and call the parseXml function.

    Collapse
    Word wrap
    Dark theme
    Copy code
    1. let options: xml.ParseOptions = {supportDoctype:true, ignoreNameSpace:true, tokenValueCallbackFunction:func};
    2. xmlParser.parseXml(options);

    The output is as follows:

    Collapse
    Word wrap
    Dark theme
    Copy code
    1. 0 0 // First digit 0: <?xml version="1.0" encoding="utf-8"?> corresponds to event type START_DOCUMENT, which value is 0; second digit 0: The depth is 0.
    2. 2 1 // First digit 2: <note importance="high" logged="true"> corresponds to event type START_TAG, which value is 2; second digit 1: The depth is 1.
    3. 2 2 // First digit 2: <title> corresponds to event type START_TAG, which value is 2; second digit 2: The depth is 2.
    4. 4 2 // First digit 4: "Play" corresponds to event type TEXT, which value is 4; second digit 2: The depth is 2.
    5. 3 2 // First digit 3: </title> corresponds to event type END_TAG, which value is 3; second digit 2: The depth is 2.
    6. 3 1 // First digit 3: </note> corresponds to event type END_TAG, which value is 3; second digit 1: The depth is 1.
    7. 1 0 // First digit 1: corresponds to event type END_DOCUMENT, which value is 1; second digit 0: The depth is 0.

Example Scenario

This example demonstrates how to use all parsing options to parse XML tags, attributes, and event types.

Collapse
Word wrap
Dark theme
Copy code
  1. import { xml, util } from '@kit.ArkTS';
  2. // ...
  3. let strXml: string =
  4. '<?xml version="1.0" encoding="UTF-8"?>' +
  5. '<book category="COOKING">' +
  6. '<title lang="en">Everyday</title>' +
  7. '<author>Giana</author>' +
  8. '</book>';
  9. let textEncoder: util.TextEncoder = new util.TextEncoder();
  10. let arrBuffer: Uint8Array = textEncoder.encodeInto(strXml);
  11. let xmlParser: xml.XmlPullParser = new xml.XmlPullParser(arrBuffer.buffer as object as ArrayBuffer, 'UTF-8');
  12. let str: string = '';
  13. function tagFunc(name: string, value: string): boolean {
  14. str = name + value;
  15. console.info('tag-' + str);
  16. return true;
  17. }
  18. function attFunc(name: string, value: string): boolean {
  19. str = name + ' ' + value;
  20. console.info('attri-' + str);
  21. return true;
  22. }
  23. function tokenFunc(name: xml.EventType, value: xml.ParseInfo): boolean {
  24. str = name + ' ' + value.getDepth();
  25. console.info('token-' + str);
  26. // ...
  27. return true;
  28. }
  29. // ...
  30. let options: xml.ParseOptions = {
  31. supportDoctype: true,
  32. ignoreNameSpace: true,
  33. tagValueCallbackFunction: tagFunc,
  34. attributeValueCallbackFunction: attFunc,
  35. tokenValueCallbackFunction: tokenFunc
  36. };
  37. xmlParser.parseXml(options);

The output is as follows:

Collapse
Word wrap
Dark theme
Copy code
  1. tag-
  2. token-0 0
  3. tag-book
  4. token-2 1
  5. attri-category COOKING
  6. tag-title
  7. token-2 2
  8. attri-lang en
  9. tag-Everyday
  10. token-4 2
  11. tag-title
  12. token-3 2
  13. tag-author
  14. token-2 2
  15. tag-Giana
  16. token-4 2
  17. tag-author
  18. token-3 2
  19. tag-book
  20. token-3 1
  21. tag-
  22. token-1 0