一、XML 解析
对于以 XML 作为载体传递的数据,实际使用中需要对相关的节点进行解析,一般包括解析XML标签和标签值、解析XML属性和属性值、解析XML事件类型和元素深度三类场景。
XML 模块提供 XmlPullParser 类对 XML 文件解析,输入为含有 XML 文本的 ArrayBuffer 或 DataView,输出为解析得到的信息。
表 1 XML 解析选项
注意事项
● XML 解析及转换需要确保传入的 XML 数据符合标准格式。
● XML 解析目前不支持按指定节点解析对应的节点值。
解析 XML 标签和标签值
1. 引入模块。
import xml from '@ohos.xml';import util from '@ohos.util'; // 需要使用util模块函数对文件编码
复制代码
2.XML 文件编码后调用 XmlPullParser。
可以基于 ArrayBuffer 构造 XmlPullParser 对象, 也可以基于 DataView 构造 XmlPullParser 对象。
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. 自定义回调函数,本例直接打印出标签及标签值。
let str = '';function func(name, value){ str = name + value; console.info(str); return true; //true:继续解析 false:停止解析}
复制代码
4. 设置解析选项,调用 parse 函数。
let options = {supportDoctype:true, ignoreNameSpace:true, tagValueCallbackFunction:func};that.parse(options);
复制代码
输出结果如下所示:
notetitlePlaytitlelensWorklensnote
复制代码
解析 XML 属性和属性值
1.引入模块。
import xml from '@ohos.xml';import util from '@ohos.util'; // 需要使用util模块函数对文件编码
复制代码
2.对 XML 文件编码后调用 XmlPullParser。
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.自定义回调函数,本例直接打印出属性及属性值。
let str = '';function func(name, value){ str += name + ' ' + value + ' '; return true; // true:继续解析 false:停止解析}
复制代码
4.设置解析选项,调用 parse 函数。
let options = {supportDoctype:true, ignoreNameSpace:true, attributeValueCallbackFunction:func};that.parse(options);console.info(str); // 一次打印出所有的属性及其值
复制代码
输出结果如下所示:
importance high logged true // note节点的属性及属性值
复制代码
解析 XML 事件类型和元素深度
1. 引入模块。
import xml from '@ohos.xml';import util from '@ohos.util'; // 需要使用util模块函数对文件编码
复制代码
2. 对 XML 文件编码后调用 XmlPullParser。
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. 自定义回调函数,本例直接打印元素事件类型及元素深度。
let str = '';function func(name, value){ str = name + ' ' + value.getDepth(); // getDepth 获取元素的当前深度 console.info(str) return true; //true:继续解析 false:停止解析}
复制代码
4. 设置解析选项,调用 parse 函数。
let options = {supportDoctype:true, ignoreNameSpace:true, tokenValueCallbackFunction:func};that.parse(options);
复制代码
输出结果如下所示:
0 0 // 0:<?xml version="1.0" encoding="utf-8"?> 对应事件类型START_DOCUMENT值为0 0:起始深度为02 1 // 2:<note importance="high" logged="true"> 对应事件类型START_TAG值为2 1:深度为12 2 // 2:<title>对应事件类型START_TAG值为2 2:深度为24 2 // 4:Play对应事件类型TEXT值为4 2:深度为23 2 // 3:</title>对应事件类型END_TAG值为3 2:深度为23 1 // 3:</note>对应事件类型END_TAG值为3 1:深度为1(与<note对应>)1 0 // 1:对应事件类型END_DOCUMENT值为1 0:深度为0场景示例
复制代码
场景示例
此处以调用所有解析选项为例,提供解析 XML 标签、属性和事件类型的开发示例。
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);
复制代码
输出结果如下所示:
tag-token-0 0tag-bookattri-category COOKINGtoken-2 1tag-titleattri-lang entoken-2 2tag-Everydaytoken-4 2tag-titletoken-3 2tag-authortoken-2 2tag-Giadatoken-4 2tag-authortoken-3 2tag-booktoken-3 1tag-token-1 0
复制代码
二、 XML 转换
将 XML 文本转换为 JavaScript 对象可以更轻松地处理和操作数据,并且更适合在 JavaScript 应用程序中使用。
语言基础类库提供 ConvertXML 类将 XML 文本转换为 JavaScript 对象,输入为待转换的 XML 字符串及转换选项,输出为转换后的 JavaScript 对象。具体转换选项可见@ohos.convertxml。
注意事项
XML 解析及转换需要确保传入的 XML 数据符合标准格式。
开发步骤
此处以 XML 转为 JavaScript 对象后获取其标签值为例,说明转换效果。
1. 引入模块。
import convertxml from '@ohos.convertxml';
复制代码
2. 输入待转换的 XML,设置转换选项。
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. 调用转换函数,打印结果。
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); // Happyconsole.info(todo); // Workconsole.info(todo2); // Play
复制代码
输出结果如下所示:
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:Happytodo:Worktodo2:Play
复制代码
评论