#鸿蒙学习大百科#如何解析XML事件类型和元素深度?

如何解析XML事件类型和元素深度?

HarmonyOS
2024-10-24 11:40:06
4768浏览
已于2024-10-24 11:40:20修改
收藏 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); // 对数据编码,防止包含中文字符乱码
let that: xml.XmlPullParser = new xml.XmlPullParser(arrBuffer.buffer as object as ArrayBuffer, 'UTF-8');
let str: string  = '';
function func(name: xml.EventType, value: xml.ParseInfo): boolean {
  str = name + ' ' + value.getDepth(); // getDepth 获取元素的当前深度
  console.info(str)
  return true; //true:继续解析 false:停止解析
}
@Entry
@Component
struct Index {
  build() {
    Column() {
      Button("解析xml的属性和属性值").onClick(() => {
        let options: xml.ParseOptions = {supportDoctype:true, ignoreNameSpace:true, tokenValueCallbackFunction:func};
        that.parse(options);
      })
    }
    .width('100%')
    .height('100%')
    .justifyContent(FlexAlign.Center)
  }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
分享
微博
QQ
微信
回复
2024-10-24 17:20:03
相关问题
#鸿蒙学习大百科#ArkTS如何生成xml
1227浏览 • 1回复 待解决