DEV Community

Cover image for XML generation
liu yang
liu yang

Posted on

XML generation

XML Generation
XML can be used as a data interchange format, supported by various systems and applications. For example, web services can pass structured data in XML format.

XML can also serve as a messaging format for communication and interaction between different nodes in distributed systems.

Precautions

XML tags must occur in pairs; generating a start tag requires generating an end tag.

XML tag pairs are case-sensitive. The start and end tags must have consistent case.

Development Steps

The XML module provides the XmlSerializer class to generate XML data. The input is a fixed-length ArrayBuffer or DataView object that stores the generated XML data.

Call different methods to write different content. For example, startElement(name: string) writes the start element tag, and setText(text: string) writes the tag value.

You can refer to the API interfaces of the XML module in @ohos.xml for detailed descriptions. Call the corresponding functions as needed to generate complete XML data.

Import the module.

import { xml, util } from '@kit.ArkTS';

Create a buffer and construct an XmlSerializer object. You can construct an XmlSerializer object based on ArrayBuffer or DataView.

// Method 1: Construct XmlSerializer based on ArrayBuffer
let arrayBuffer: ArrayBuffer = new ArrayBuffer(2048);
let serializer: xml.XmlSerializer = new xml.XmlSerializer(arrayBuffer);

// Method 2: Construct XmlSerializer based on DataView
// let arrayBuffer: ArrayBuffer = new ArrayBuffer(2048);
// let dataView: DataView = new DataView(arrayBuffer);
// let serializer: xml.XmlSerializer = new xml.XmlSerializer(dataView);

Call XML element generation functions.

serializer.setDeclaration();
serializer.startElement('bookstore');
serializer.startElement('book');
serializer.setAttributes('category', 'COOKING');
serializer.startElement('title');
serializer.setAttributes('lang', 'en');
serializer.setText('Everyday');
serializer.endElement();
serializer.startElement('author');
serializer.setText('Giana');
serializer.endElement();
serializer.startElement('year');
serializer.setText('2005');
serializer.endElement();
serializer.endElement();
serializer.endElement();

Use Uint8Array to operate on ArrayBuffer, decode Uint8Array with TextDecoder, and output.

let uint8Array: Uint8Array = new Uint8Array(arrayBuffer);
let textDecoder: util.TextDecoder = util.TextDecoder.create();
let result: string = textDecoder.decodeToString(uint8Array);
console.info(result);

The output is as follows:

<?xml version="1.0" encoding="utf-8"?><bookstore>
  <book category="COOKING">
    <title lang="en">Everyday</title>
    <author>Giana</author>
    <year>2005</year>
  </book>
</bookstore>
Enter fullscreen mode Exit fullscreen mode

Top comments (0)