#鸿蒙学习大百科#如何解析XML属性和属性值?

如何解析XML属性和属性值?

HarmonyOS
2024-10-24 11:36:11
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
福娃泡泡
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)
  }
}
分享
微博
QQ
微信
回复
2024-10-24 15:57:34
相关问题
#鸿蒙学习大百科#ArkTS如何生成xml
198浏览 • 1回复 待解决