一、XML解析

对于以XML作为载体传递的数据,实际使用中需要对相关的节点进行解析,一般包括解析XML标签和标签值、解析XML属性和属性值、解析XML事件类型和元素深度三类场景。

XML模块提供XmlPullParser类对XML文件解析,输入为含有XML文本的ArrayBuffer或DataView,输出为解析得到的信息。

表1 XML解析选项

名称类型必填说明
supportDoctypeboolean是否忽略文档类型。默认为false,表示对文档类型进行解析。
ignoreNameSpaceboolean是否忽略命名空间。默认为false,表示对命名空间进行解析。
tagValueCallbackFunction(name: string, value: string) => boolean获取tagValue回调函数,打印标签及标签值。默认为null,表示不进行XML标签和标签值的解析。
attributeValueCallbackFunction(name: string, value: string) => boolean获取attributeValue回调函数, 打印属性及属性值。默认为null,表示不进行XML属性和属性值的解析。
tokenValueCallbackFunction(eventType: EventType, value: ParseInfo) => boolean获取tokenValue回调函数,打印标签事件类型及parseInfo对应属性。默认为null,表示不进行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 =  '' +    '' +    'Play' +    'Work' +    '';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 =  '' +    '' +    '    Play' +    '    Happy' +    '    Work' +    '';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 =  '' +  '' +  'Play' +  '';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: 对应事件类型START_DOCUMENT值为0  0:起始深度为02 1 // 2: 对应事件类型START_TAG值为2       1:深度为12 2 // 2:对应事件类型START_TAG值为2                                       2:深度为24 2 // 4:Play对应事件类型TEXT值为4                                               2:深度为23 2 // 3:对应事件类型END_TAG值为3                                        2:深度为23 1 // 3:对应事件类型END_TAG值为3                                         1:深度为1(与)1 0 // 1:对应事件类型END_DOCUMENT值为1                                           0:深度为0场景示例

场景示例

此处以调用所有解析选项为例,提供解析XML标签、属性和事件类型的开发示例。

import xml from '@ohos.xml';import util from '@ohos.util';let strXml =  '' +    '' +    'Everyday' +    'Giada' +    '';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 =  '' +    '' +    '    Happy' +    '    Work' +    '    Play' +    '';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']; // 解析标签对应的值let todo = result['_elements'][0]['_elements'][1]['_elements'][0]['_text']; // 解析标签对应的值let todo2 = result['_elements'][0]['_elements'][2]['_elements'][0]['_text']; // 解析标签对应的值console.info(title); // Happyconsole.info(todo); // Workconsole.info(todo2); // Play</code></pre><p>输出结果如下所示:</p><pre><code>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</code></pre><blockquote><p>本文由博客一文多发平台 OpenWrite 发布!</p></blockquote></article></div><div class="related-posts"><h2 class="related-posts-title"><i class="fab fa-hive me-1"></i>相关文章</h2><div class="row g-2 g-md-3 row-cols-2 row-cols-md-3 row-cols-lg-4"><div class="col"><article class="post-item item-grid"><div class="tips-badge position-absolute top-0 start-0 z-1 m-2"></div><div class="entry-media ratio ratio-3x2"> <a target="" class="media-img lazy bg-cover bg-center" href="https://www.maxssl.com/article/30076/" title="C静态库的创建与使用–为什么要引入静态库?" data-bg="https://img.maxssl.com/uploads/?url=https://img2023.cnblogs.com/blog/2431966/202310/2431966-20231010234118982-1597176513.png"> </a></div><div class="entry-wrapper"><h2 class="entry-title"> <a target="" href="https://www.maxssl.com/article/30076/" title="C静态库的创建与使用–为什么要引入静态库?">C静态库的创建与使用–为什么要引入静态库?</a></h2></div></article></div><div class="col"><article class="post-item item-grid"><div class="tips-badge position-absolute top-0 start-0 z-1 m-2"></div><div class="entry-media ratio ratio-3x2"> <a target="" class="media-img lazy bg-cover bg-center" href="https://www.maxssl.com/article/16758/" title="MySQL 8.0不再担心被垃圾SQL搞爆内存" data-bg="https://img.maxssl.com/uploads/?url=https://img2023.cnblogs.com/other/2630741/202305/2630741-20230516074615020-549610325.png"> </a></div><div class="entry-wrapper"><h2 class="entry-title"> <a target="" href="https://www.maxssl.com/article/16758/" title="MySQL 8.0不再担心被垃圾SQL搞爆内存">MySQL 8.0不再担心被垃圾SQL搞爆内存</a></h2></div></article></div><div class="col"><article class="post-item item-grid"><div class="tips-badge position-absolute top-0 start-0 z-1 m-2"></div><div class="entry-media ratio ratio-3x2"> <a target="" class="media-img lazy bg-cover bg-center" href="https://www.maxssl.com/article/32904/" title="读程序员的制胜技笔记11_与Bug共存(上)" data-bg="https://img.maxssl.com/uploads/?url=https://img2023.cnblogs.com/blog/3076680/202311/3076680-20231112214712110-538352444.png"> </a></div><div class="entry-wrapper"><h2 class="entry-title"> <a target="" href="https://www.maxssl.com/article/32904/" title="读程序员的制胜技笔记11_与Bug共存(上)">读程序员的制胜技笔记11_与Bug共存(上)</a></h2></div></article></div><div class="col"><article class="post-item item-grid"><div class="tips-badge position-absolute top-0 start-0 z-1 m-2"></div><div class="entry-media ratio ratio-3x2"> <a target="" class="media-img lazy bg-cover bg-center" href="https://www.maxssl.com/article/20736/" title="Golang 中的 strings 包详解(一):strings.Builder" data-bg="/wp-content/themes/ripro-v5/assets/img/thumb.jpg"> </a></div><div class="entry-wrapper"><h2 class="entry-title"> <a target="" href="https://www.maxssl.com/article/20736/" title="Golang 中的 strings 包详解(一):strings.Builder">Golang 中的 strings 包详解(一):strings.Builder</a></h2></div></article></div><div class="col"><article class="post-item item-grid"><div class="tips-badge position-absolute top-0 start-0 z-1 m-2"></div><div class="entry-media ratio ratio-3x2"> <a target="" class="media-img lazy bg-cover bg-center" href="https://www.maxssl.com/article/10973/" title="Vulnhub之BoredHackerBlog: Social Network_Medium Socnet详细测试过程(拿到root shell)" data-bg="/wp-content/themes/ripro-v5/assets/img/thumb.jpg"> </a></div><div class="entry-wrapper"><h2 class="entry-title"> <a target="" href="https://www.maxssl.com/article/10973/" title="Vulnhub之BoredHackerBlog: Social Network_Medium Socnet详细测试过程(拿到root shell)">Vulnhub之BoredHackerBlog: Social Network_Medium Socnet详细测试过程(拿到root shell)</a></h2></div></article></div><div class="col"><article class="post-item item-grid"><div class="tips-badge position-absolute top-0 start-0 z-1 m-2"></div><div class="entry-media ratio ratio-3x2"> <a target="" class="media-img lazy bg-cover bg-center" href="https://www.maxssl.com/article/32593/" title="解锁云计算的未来:AI、容器和数据隐私的挑战" data-bg="/wp-content/themes/ripro-v5/assets/img/thumb.jpg"> </a></div><div class="entry-wrapper"><h2 class="entry-title"> <a target="" href="https://www.maxssl.com/article/32593/" title="解锁云计算的未来:AI、容器和数据隐私的挑战">解锁云计算的未来:AI、容器和数据隐私的挑战</a></h2></div></article></div><div class="col"><article class="post-item item-grid"><div class="tips-badge position-absolute top-0 start-0 z-1 m-2"></div><div class="entry-media ratio ratio-3x2"> <a target="" class="media-img lazy bg-cover bg-center" href="https://www.maxssl.com/article/22603/" title="布隆(Bloom Filter)过滤器——全面讲解,建议收藏" data-bg="https://img.maxssl.com/uploads/?url=https://img-blog.csdnimg.cn/img_convert/8ef4dd0de55a1da3d9d66298ddbd9d3f.png"> </a></div><div class="entry-wrapper"><h2 class="entry-title"> <a target="" href="https://www.maxssl.com/article/22603/" title="布隆(Bloom Filter)过滤器——全面讲解,建议收藏">布隆(Bloom Filter)过滤器——全面讲解,建议收藏</a></h2></div></article></div><div class="col"><article class="post-item item-grid"><div class="tips-badge position-absolute top-0 start-0 z-1 m-2"></div><div class="entry-media ratio ratio-3x2"> <a target="" class="media-img lazy bg-cover bg-center" href="https://www.maxssl.com/article/7855/" title="pmp培训机构哪个好?各pmp培训机构排名如何?" data-bg="https://csdnimg.cn/release/blog_editor_html/release1.9.5/ckeditor/plugins/CsdnLink/icons/icon-default.png"> </a></div><div class="entry-wrapper"><h2 class="entry-title"> <a target="" href="https://www.maxssl.com/article/7855/" title="pmp培训机构哪个好?各pmp培训机构排名如何?">pmp培训机构哪个好?各pmp培训机构排名如何?</a></h2></div></article></div></div></div></div><div class="sidebar-wrapper col-md-12 col-lg-3 h-100" data-sticky><div class="sidebar"><div id="recent-posts-4" class="widget widget_recent_entries"><h5 class="widget-title">最新关注</h5><ul><li> <a href="https://www.maxssl.com/article/57859/">【MySQL】InnoDB存储引擎</a></li><li> <a href="https://www.maxssl.com/article/57858/">DB-GPT:强强联合Langchain-Vicuna的应用实战开源项目,彻底改变与数据库的交互方式</a></li><li> <a href="https://www.maxssl.com/article/57857/">TigerBeetle:世界上最快的会计数据库</a></li><li> <a href="https://www.maxssl.com/article/57856/">【SQL server】玩转SQL server数据库:第三章 关系数据库标准语言SQL(二)数据查询</a></li><li> <a href="https://www.maxssl.com/article/57855/">马斯克400条聊天记录被法院公开,原来推特收购是在短信上谈崩的</a></li><li> <a href="https://www.maxssl.com/article/57854/">戏精摩根大通:从唱空比特币到牵手贝莱德</a></li></ul></div><div id="ri_sidebar_posts_widget-2" class="widget sidebar-posts-list"><h5 class="widget-title">热文推荐</h5><div class="row g-3 row-cols-1"><div class="col"><article class="post-item item-list"><div class="entry-media ratio ratio-3x2 col-auto"> <a target="" class="media-img lazy" href="https://www.maxssl.com/article/40712/" title="HTML与JavaScript实现注册页面" data-bg="https://img.maxssl.com/uploads/?url=https://img-blog.csdnimg.cn/83cefe4815614071a4d0ffeb5c1d68bb.gif"></a></div><div class="entry-wrapper"><div class="entry-body"><h2 class="entry-title"> <a target="" href="https://www.maxssl.com/article/40712/" title="HTML与JavaScript实现注册页面">HTML与JavaScript实现注册页面</a></h2></div></div></article></div><div class="col"><article class="post-item item-list"><div class="entry-media ratio ratio-3x2 col-auto"> <a target="" class="media-img lazy" href="https://www.maxssl.com/article/50660/" title="【手写数据库toadb】虚拟文件描述符,连接表对象与物理文件的纽带,通过逻辑表找到物理文件的密码" data-bg="/wp-content/themes/ripro-v5/assets/img/thumb.jpg"></a></div><div class="entry-wrapper"><div class="entry-body"><h2 class="entry-title"> <a target="" href="https://www.maxssl.com/article/50660/" title="【手写数据库toadb】虚拟文件描述符,连接表对象与物理文件的纽带,通过逻辑表找到物理文件的密码">【手写数据库toadb】虚拟文件描述符,连接表对象与物理文件的纽带,通过逻辑表找到物理文件的密码</a></h2></div></div></article></div><div class="col"><article class="post-item item-list"><div class="entry-media ratio ratio-3x2 col-auto"> <a target="" class="media-img lazy" href="https://www.maxssl.com/article/21161/" title="EasyX快速入门" data-bg="https://img.maxssl.com/uploads/?url=https://img-blog.csdnimg.cn/1bd89dbbc06d4d44a92730e624c1d7bd.gif"></a></div><div class="entry-wrapper"><div class="entry-body"><h2 class="entry-title"> <a target="" href="https://www.maxssl.com/article/21161/" title="EasyX快速入门">EasyX快速入门</a></h2></div></div></article></div><div class="col"><article class="post-item item-list"><div class="entry-media ratio ratio-3x2 col-auto"> <a target="" class="media-img lazy" href="https://www.maxssl.com/article/55728/" title="网络编程(IP、端口、协议、UDP、TCP)【详解】" data-bg="https://img.maxssl.com/uploads/?url=https://img-blog.csdnimg.cn/direct/c34d6e606f334b5b9875f66c5c9915c8.png"></a></div><div class="entry-wrapper"><div class="entry-body"><h2 class="entry-title"> <a target="" href="https://www.maxssl.com/article/55728/" title="网络编程(IP、端口、协议、UDP、TCP)【详解】">网络编程(IP、端口、协议、UDP、TCP)【详解】</a></h2></div></div></article></div><div class="col"><article class="post-item item-list"><div class="entry-media ratio ratio-3x2 col-auto"> <a target="" class="media-img lazy" href="https://www.maxssl.com/article/53166/" title="ASP.NET Core中的依赖问题解决方法示例" data-bg="/wp-content/themes/ripro-v5/assets/img/thumb.jpg"></a></div><div class="entry-wrapper"><div class="entry-body"><h2 class="entry-title"> <a target="" href="https://www.maxssl.com/article/53166/" title="ASP.NET Core中的依赖问题解决方法示例">ASP.NET Core中的依赖问题解决方法示例</a></h2></div></div></article></div><div class="col"><article class="post-item item-list"><div class="entry-media ratio ratio-3x2 col-auto"> <a target="" class="media-img lazy" href="https://www.maxssl.com/article/11923/" title="使用Pytorch进行多卡训练" data-bg="https://img.maxssl.com/uploads/?url=https://img-blog.csdnimg.cn/img_convert/feeb266ad6981509e91180e6fd710465.png"></a></div><div class="entry-wrapper"><div class="entry-body"><h2 class="entry-title"> <a target="" href="https://www.maxssl.com/article/11923/" title="使用Pytorch进行多卡训练">使用Pytorch进行多卡训练</a></h2></div></div></article></div></div></div></div></div></div></div></main><footer class="site-footer py-md-4 py-2 mt-2 mt-md-4"><div class="container"><div class="text-center small w-100"><div>Copyright © <script>today=new Date();document.write(today.getFullYear());</script> maxssl.com 版权所有 <a href="https://beian.miit.gov.cn/" target="_blank" rel="nofollow noopener">浙ICP备2022011180号</a></div><div class=""><script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-7656930379472324"
     crossorigin="anonymous"></script></div></div></div></footer><div class="rollbar"><ul class="actions"><li><a target="" href="https://www.maxssl.com/" rel="nofollow noopener noreferrer"><i class="fas fa-home"></i><span></span></a></li><li><a target="" href="http://wpa.qq.com/msgrd?v=3&uin=6666666&site=qq&menu=yes" rel="nofollow noopener noreferrer"><i class="fab fa-qq"></i><span></span></a></li></ul></div><div class="back-top"><i class="fas fa-caret-up"></i></div><div class="dimmer"></div><div class="off-canvas"><div class="canvas-close"><i class="fas fa-times"></i></div><div class="logo-wrapper"> <a class="logo text" href="https://www.maxssl.com/">MaxSSL</a></div><div class="mobile-menu d-block d-lg-none"></div></div> <script></script><noscript><style>.lazyload{display:none}</style></noscript><script data-noptimize="1">window.lazySizesConfig=window.lazySizesConfig||{};window.lazySizesConfig.loadMode=1;</script><script async data-noptimize="1" src='https://www.maxssl.com/wp-content/plugins/autoptimize/classes/external/js/lazysizes.min.js'></script><script src='//cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js' id='jquery-js'></script> <script src='//cdn.bootcdn.net/ajax/libs/highlight.js/11.7.0/highlight.min.js' id='highlight-js'></script> <script src='https://www.maxssl.com/wp-content/themes/ripro-v5/assets/js/vendor.min.js' id='vendor-js'></script> <script id='main-js-extra'>var zb={"home_url":"https:\/\/www.maxssl.com","ajax_url":"https:\/\/www.maxssl.com\/wp-admin\/admin-ajax.php","theme_url":"https:\/\/www.maxssl.com\/wp-content\/themes\/ripro-v5","singular_id":"29310","post_content_nav":"0","site_notify_auto":"0","current_user_id":"0","ajax_nonce":"174e59daba","gettext":{"__copypwd":"\u5bc6\u7801\u5df2\u590d\u5236\u526a\u8d34\u677f","__copybtn":"\u590d\u5236","__copy_succes":"\u590d\u5236\u6210\u529f","__comment_be":"\u63d0\u4ea4\u4e2d...","__comment_succes":"\u8bc4\u8bba\u6210\u529f","__comment_succes_n":"\u8bc4\u8bba\u6210\u529f\uff0c\u5373\u5c06\u5237\u65b0\u9875\u9762","__buy_be_n":"\u8bf7\u6c42\u652f\u4ed8\u4e2d\u00b7\u00b7\u00b7","__buy_no_n":"\u652f\u4ed8\u5df2\u53d6\u6d88","__is_delete_n":"\u786e\u5b9a\u5220\u9664\u6b64\u8bb0\u5f55\uff1f"}};</script> <script src='https://www.maxssl.com/wp-content/themes/ripro-v5/assets/js/main.min.js' id='main-js'></script> </body></html>