DEV Community

Cover image for XML Conversion
liu yang
liu yang

Posted on • Edited on

XML Conversion

XML Conversion: Transforming XML Text into JavaScript Objects

Converting XML text to JavaScript objects is a crucial task in modern web development, especially when dealing with data interchange between different systems or integrating with APIs that return XML responses. This process allows developers to handle and manipulate data more efficiently within JavaScript applications. The language foundation library in HarmonyOS provides the ConvertXML class specifically designed to transform XML text into JavaScript objects. This article will walk you through the detailed steps and considerations involved in this conversion process.

Precautions and Best Practices

Before diving into the conversion process, it is essential to ensure that the input XML data adheres to the standard XML format. This includes proper nesting of elements, correct use of tags, and appropriate handling of special characters. For instance, any & characters in the XML text should be replaced with the entity reference & to avoid parsing errors. Additionally, the XML document should have a single root element, and all tags should be properly closed.

Development Steps

The following example demonstrates how to convert XML text to a JavaScript object and retrieve tag values to illustrate the conversion effect.

Step 1: Import the Module

First, you need to import the convertxml module from the HarmonyOS language foundation library.

import { convertxml } from '@kit.ArkTS';
Enter fullscreen mode Exit fullscreen mode

Step 2: Input the XML to be Converted and Set Conversion Options

The input XML text should be a well-formed XML string. You also need to define the conversion options, which determine how the XML data is transformed into a JavaScript object. For detailed information on supported conversion options, refer to the ConvertOptions interface in the API documentation at @ohos.convertxml.

Note: In the input XML text, replace any & characters with the entity reference &.

let xml: string =
 '<?xml version="1.0" encoding="utf-8"?>' +
 '<note importance="high" logged="true">' +
 '    <title>Happy</title>' +
 '    <todo>Work</todo>' +
 '    <todo>Play</todo>' +
 '</note>';

let options: convertxml.ConvertOptions = {
  trim: false,
  declarationKey: "_declaration",
  instructionKey: "_instruction",
  attributesKey: "_attributes",
  textKey: "_text",
  cdataKey: "_cdata",
  doctypeKey: "_doctype",
  commentKey: "_comment",
  parentKey: "_parent",
  typeKey: "_type",
  nameKey: "_name",
  elementsKey: "_elements"
};
Enter fullscreen mode Exit fullscreen mode

Step 3: Call the Conversion Function and Print the Result

Next, create an instance of the ConvertXML class and call the convertToJSObject method to perform the conversion. The result is a JavaScript object that can be easily manipulated or converted to a JSON string for explicit output.

let conv: convertxml.ConvertXML = new convertxml.ConvertXML();
let result: object = conv.convertToJSObject(xml, options);
let strRes: string = JSON.stringify(result, null, 2); // Convert the JavaScript object to a JSON string with indentation for better readability
console.info(strRes);
Enter fullscreen mode Exit fullscreen mode

Output Result

The output result is a JSON representation of the converted XML data. This JSON object can be easily parsed and manipulated within JavaScript applications.

{
  "_declaration": {
    "_attributes": {
      "version": "1.0",
      "encoding": "utf-8"
    }
  },
  "_elements": [
    {
      "_type": "element",
      "_name": "note",
      "_attributes": {
        "importance": "high",
        "logged": "true"
      },
      "_elements": [
        {
          "_type": "element",
          "_name": "title",
          "_elements": [
            {
              "_type": "text",
              "_text": "Happy"
            }
          ]
        },
        {
          "_type": "element",
          "_name": "todo",
          "_elements": [
            {
              "_type": "text",
              "_text": "Work"
            }
          ]
        },
        {
          "_type": "element",
          "_name": "todo",
          "_elements": [
            {
              "_type": "text",
              "_text": "Play"
            }
          ]
        }
      ]
    }
  ]
}
Enter fullscreen mode Exit fullscreen mode

Detailed Explanation

  1. Importing the Module:
   import { convertxml } from '@kit.ArkTS';
Enter fullscreen mode Exit fullscreen mode

This line imports the convertxml module, which contains the ConvertXML class and related interfaces.

  1. Defining the XML String:
   let xml: string =
   '<?xml version="1.0" encoding="utf-8"?>' +
   '<note importance="high" logged="true">' +
   '    <title>Happy</title>' +
   '    <todo>Work</todo>' +
   '    <todo>Play</todo>' +
   '</note>';
Enter fullscreen mode Exit fullscreen mode

This XML string includes a declaration, a root element <note> with attributes, and nested elements <title> and <todo>.

  1. Setting Conversion Options:
   let options: convertxml.ConvertOptions = {
     trim: false,
     declarationKey: "_declaration",
     instructionKey: "_instruction",
     attributesKey: "_attributes",
     textKey: "_text",
     cdataKey: "_cdata",
     doctypeKey: "_doctype",
     commentKey: "_comment",
     parentKey: "_parent",
     typeKey: "_type",
     nameKey: "_name",
     elementsKey: "_elements"
   };
Enter fullscreen mode Exit fullscreen mode

These options define how the XML data is transformed into a JavaScript object. For example, declarationKey specifies the key for the XML declaration, and attributesKey specifies the key for element attributes.

  1. Performing the Conversion:
   let conv: convertxml.ConvertXML = new convertxml.ConvertXML();
   let result: object = conv.convertToJSObject(xml, options);
Enter fullscreen mode Exit fullscreen mode

The convertToJSObject method takes the XML string and conversion options as input and returns a JavaScript object.

  1. Converting to JSON and Printing the Result:
   let strRes: string = JSON.stringify(result, null, 2);
   console.info(strRes);
Enter fullscreen mode Exit fullscreen mode

The JSON.stringify method converts the JavaScript object to a JSON string with indentation for better readability. The result is then printed to the console.

Practical Use Cases

  1. Data Interchange:
    XML is commonly used for data interchange between different systems. Converting XML to JavaScript objects allows for easier data manipulation and integration within JavaScript applications.

  2. Configuration Files:
    Many applications use XML files for configuration settings. Converting these XML files to JavaScript objects makes it easier to read and modify configuration data dynamically.

  3. Web Services:
    When working with web services that return XML responses, converting the XML data to JavaScript objects simplifies the process of extracting and using the data in your application.

Conclusion

Converting XML text to JavaScript objects is a powerful technique that enhances data handling and manipulation in JavaScript applications. The ConvertXML class provided by the HarmonyOS language foundation library simplifies this process by offering a robust and flexible conversion mechanism. By following the steps outlined in this article, you can easily transform XML data into JavaScript objects, making it more suitable for use in modern web development. For more detailed information on conversion options and advanced usage, refer to the official API documentation at @ohos.convertxml.

Top comments (1)

Some comments may only be visible to logged-in visitors. Sign in to view all comments.