中国优质的IT技术网站
专业IT技术创作平台
IT职业在线教育平台
如何解析XML属性和属性值?
微信扫码分享
import xml from '@ohos.xml'; import util from '@ohos.util'; // 需要使用util模块函数对文件编码 let strXml: string = '<?xml version="1.0" encoding="utf-8"?>' + '<note importance="high" logged="true">' + '<title>Play</title>' + '<lens>Work</lens>' + '</note>'; let textEncoder: util.TextEncoder = new util.TextEncoder(); let arrBuffer: Uint8Array = textEncoder.encodeInto(strXml); // 对数据编码,防止包含中文字符乱码 // 1.基于ArrayBuffer构造XmlPullParser对象 let that: xml.XmlPullParser = new xml.XmlPullParser(arrBuffer.buffer as object as ArrayBuffer, 'UTF-8'); // 2.基于DataView构造XmlPullParser对象 // let dataView: DataView = new DataView(arrBuffer.buffer as object as ArrayBuffer); // let that: xml.XmlPullParser = new xml.XmlPullParser(dataView, 'UTF-8'); let str: string = ''; function func(name: string, value: string): boolean { str += name + ' ' + value + ' '; return true; // true:继续解析 false:停止解析 } @Entry @Component struct Index { build() { Column() { Button("解析xml的属性和属性值").onClick(() => { let options: xml.ParseOptions = {supportDoctype:true, ignoreNameSpace:true, attributeValueCallbackFunction:func}; that.parse(options); }) } .width('100%') .height('100%') .justifyContent(FlexAlign.Center) } }