[Mid-Autumn Festival and National Day constantly updated] XML generation, parsing and conversion in HarmonyOS (Part 2)

1. XML parsing

For data transmitted using XML as a carrier, the relevant nodes need to be parsed in actual use, which generally includes three scenarios: parsing XML tags and tag values , parsing XML attributes and attribute values , and parsing XML event types and element depths .

The XML module provides the XmlPullParser class to parse XML files. The input is an ArrayBuffer or DataView containing XML text, and the output is the parsed information.

Table 1  XML parsing options

name

type

Required

illustrate

supportDoctype

boolean

no

Whether to ignore document types. The default is false, which means the document type is parsed.

ignoreNameSpace

boolean

no

Whether to ignore namespaces. The default is false, which means the namespace is parsed.

tagValueCallbackFunction

(name: string, value: string) => boolean

no

Get the tagValue callback function and print the tag and tag value. The default is null, which means that XML tags and tag values ​​will not be parsed.

attributeValueCallbackFunction

(name: string, value: string) => boolean

no

Get the attributeValue callback function and print the attribute and attribute value. The default is null, which means that XML attributes and attribute values ​​will not be parsed.

tokenValueCallbackFunction

(eventType: EventType, value: ParseInfo) => boolean

no

Get the tokenValue callback function and print the tag event type and parseInfo corresponding attributes. The default is null, which means no XML event type parsing is performed.

Precautions

  • XML parsing and conversion need to ensure that the incoming XML data conforms to a standard format.
  • XML parsing currently does not support parsing the corresponding node value according to the specified node.

Parse XML tags and tag values

  1. Import modules.
import xml from '@ohos.xml';
import util from '@ohos.util'; // 需要使用util模块函数对文件编码

2. Call XmlPullParser after encoding the XML file.

The XmlPullParser object can be constructed based on ArrayBuffer, or the XmlPullParser object can be constructed based on DataView.

let strXml =
  '<?xml version="1.0" encoding="utf-8"?>' +
    '<note importance="high" logged="true">' +
    '<title>Play</title>' +
    '<lens>Work</lens>' +
    '</note>';
let textEncoder = new util.TextEncoder();
let arrBuffer = textEncoder.encodeInto(strXml); // 对数据编码,防止包含中文字符乱码
// 1.基于ArrayBuffer构造XmlPullParser对象
let that = new xml.XmlPullParser(arrBuffer.buffer, 'UTF-8');

// 2.基于DataView构造XmlPullParser对象
let dataView = new DataView(arrBuffer.buffer);
let that = new xml.XmlPullParser(dataView, 'UTF-8');

3. Customize the callback function. In this example, the label and label value are printed directly.

let str = '';
function func(name, value){
       
       
  str = name + value;
  console.info(str);
  return true; //true:继续解析 false:停止解析
}

4. Set the parsing options and call the parse function.

let options = {supportDoctype:true, ignoreNameSpace:true, tagValueCallbackFunction:func};
that.parse(options);

The output is as follows:

note
title
Play
title
lens
Work
lens
note

Parse XML attributes and attribute values

1.Introduce modules.

import xml from '@ohos.xml';
import util from '@ohos.util'; // 需要使用util模块函数对文件编码

2. Call XmlPullParser after encoding the XML file.

let strXml =
  '<?xml version="1.0" encoding="utf-8"?>' +
    '<note importance="high" logged="true">' +
    '    <title>Play</title>' +
    '    <title>Happy</title>' +
    '    <lens>Work</lens>' +
    '</note>';
let textEncoder = new util.TextEncoder();
let arrBuffer = textEncoder.encodeInto(strXml); // 对数据编码,防止包含中文字符乱码
let that = new xml.XmlPullParser(arrBuffer.buffer, 'UTF-8');


3. Customize the callback function. In this example, the attributes and attribute values ​​are printed directly.

let str = '';
function func(name, value){
       
       
  str += name + ' ' + value + ' ';
  return true; // true:继续解析 false:停止解析
}


4. Set the parsing options and call the parse function.

let options = {supportDoctype:true, ignoreNameSpace:true, attributeValueCallbackFunction:func};
that.parse(options);
console.info(str); // 一次打印出所有的属性及其值

The output is as follows:

importance high logged true // note节点的属性及属性值

Parsing XML event types and element depth

  1. Import modules.
import xml from '@ohos.xml';
import util from '@ohos.util'; // 需要使用util模块函数对文件编码

2. Call XmlPullParser after encoding the XML file.

let strXml =
  '<?xml version="1.0" encoding="utf-8"?>' +
  '<note importance="high" logged="true">' +
  '<title>Play</title>' +
  '</note>';
let textEncoder = new util.TextEncoder();
let arrBuffer = textEncoder.encodeInto(strXml); // 对数据编码,防止包含中文字符乱码
let that = new xml.XmlPullParser(arrBuffer.buffer, 'UTF-8');

3. Customize the callback function. In this example, the element event type and element depth are directly printed.

let str = '';
function func(name, value){
       
       
  str = name + ' ' + value.getDepth(); // getDepth 获取元素的当前深度
  console.info(str)
  return true; //true:继续解析 false:停止解析
}

4. Set the parsing options and call the parse function.

let options = {supportDoctype:true, ignoreNameSpace:true, tokenValueCallbackFunction:func};
that.parse(options);

The output is as follows:

0 0 // 0:<?xml version="1.0" encoding="utf-8"?> 对应事件类型START_DOCUMENT值为0  0:起始深度为0
2 1 // 2:<note importance="high" logged="true"> 对应事件类型START_TAG值为2       1:深度为1
2 2 // 2:<title>对应事件类型START_TAG值为2                                       2:深度为2
4 2 // 4:Play对应事件类型TEXT值为4                                               2:深度为2
3 2 // 3:</title>对应事件类型END_TAG值为3                                        2:深度为2
3 1 // 3:</note>对应事件类型END_TAG值为3                                         1:深度为1(与<note对应>)
1 0 // 1:对应事件类型END_DOCUMENT值为1                                           0:深度为0
场景示例

Scenario example

Here, we take calling all parsing options as an example to provide development examples for parsing XML tags, attributes, and event types.

import xml from '@ohos.xml';
import util from '@ohos.util';

let strXml =
  '<?xml version="1.0" encoding="UTF-8"?>' +
    '<book category="COOKING">' +
    '<title lang="en">Everyday</title>' +
    '<author>Giada</author>' +
    '</book>';
let textEncoder = new util.TextEncoder();
let arrBuffer = textEncoder.encodeInto(strXml);
let that = new xml.XmlPullParser(arrBuffer.buffer, 'UTF-8');
let str = '';

function tagFunc(name, value) {
       
       
  str = name + value;
  console.info('tag-' + str);
  return true;
}

function attFunc(name, value) {
       
       
  str = name + ' ' + value;
  console.info('attri-' + str);
  return true;
}

function tokenFunc(name, value) {
       
       
  str = name + ' ' + value.getDepth();
  console.info('token-' + str);
  return true;
}

let options = {
       
       
  supportDocType: true,
  ignoreNameSpace: true,
  tagValueCallbackFunction: tagFunc,
  attributeValueCallbackFunction: attFunc,
  tokenValueCallbackFunction: tokenFunc
};
that.parse(options);

The output is as follows:

tag-
token-0 0
tag-book
attri-category COOKING
token-2 1
tag-title
attri-lang en
token-2 2
tag-Everyday
token-4 2
tag-title
token-3 2
tag-author
token-2 2
tag-Giada
token-4 2
tag-author
token-3 2
tag-book
token-3 1
tag-
token-1 0

2. XML conversion

Converting XML text into JavaScript objects makes the data easier to process and manipulate, and is more suitable for use in JavaScript applications.

The language basic class library provides the ConvertXML class to convert XML text into JavaScript objects. The input is the XML string to be converted and the conversion options, and the output is the converted JavaScript object. Specific conversion options can be found in @ohos.convertxml .

Precautions

XML parsing and conversion need to ensure that the incoming XML data conforms to a standard format.

Development steps

Here, we use the example of obtaining the tag value after converting XML into a JavaScript object to illustrate the conversion effect.

  1. Import modules.
import convertxml from '@ohos.convertxml';

2. Enter the XML to be converted and set the conversion options.

let xml =
  '<?xml version="1.0" encoding="utf-8"?>' +
    '<note importance="high" logged="true">' +
    '    <title>Happy</title>' +
    '    <todo>Work</todo>' +
    '    <todo>Play</todo>' +
    '</note>';
let options = {
       
       
  // trim: false 转换后是否删除文本前后的空格,否
  // declarationKey: "_declaration" 转换后文件声明使用_declaration来标识
  // instructionKey: "_instruction" 转换后指令使用_instruction标识
  // attributesKey: "_attributes" 转换后属性使用_attributes标识
  // textKey: "_text" 转换后标签值使用_text标识
  // cdataKey: "_cdata" 转换后未解析数据使用_cdata标识
  // docTypeKey: "_doctype" 转换后文档类型使用_doctype标识
  // commentKey: "_comment" 转换后注释使用_comment标识
  // parentKey: "_parent" 转换后父类使用_parent标识
  // typeKey: "_type" 转换后元素类型使用_type标识
  // nameKey: "_name" 转换后标签名称使用_name标识
  // elementsKey: "_elements" 转换后元素使用_elements标识
  trim: false,
  declarationKey: "_declaration",
  instructionKey: "_instruction",
  attributesKey: "_attributes",
  textKey: "_text",
  cdataKey: "_cdata",
  docTypeKey: "_doctype",
  commentKey: "_comment",
  parentKey: "_parent",
  typeKey: "_type",
  nameKey: "_name",
  elementsKey: "_elements"
}

3. Call the conversion function and print the result.

let conv = new convertxml.ConvertXML();
let result = conv.convertToJSObject(xml, options);
let strRes = JSON.stringify(result); // 将js对象转换为json字符串,用于显式输出
console.info(strRes);
// 也可以直接处理转换后的JS对象,获取标签值
let title = result['_elements'][0]['_elements'][0]['_elements'][0]['_text']; // 解析<title>标签对应的值
let todo = result['_elements'][0]['_elements'][1]['_elements'][0]['_text']; // 解析<todo>标签对应的值
let todo2 = result['_elements'][0]['_elements'][2]['_elements'][0]['_text']; // 解析<todo>标签对应的值
console.info(title); // Happy
console.info(todo); // Work
console.info(todo2); // Play

The output is as follows:

strRes:
{
       
       "_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"}]}]}]}
title:Happy
todo:Work
todo2:Play

Guess you like

Origin blog.csdn.net/HarmonyOSDev/article/details/133312798
Recommended