• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# UI框架(JS)开发常见问题
2
3## 如何取出xml文件中对应的字段
4
5适用于:OpenHarmony SDK 3.2.3.5版本, API9 Stage模型
6
7convertxml中convert方法提供了转换xml文本为JavaScript对象的能力。
8
9示例:
10
11
12```
13import convertxml from '@ohos.convertxml';
14// xml格式的字符串
15let xml =
16  '<?xml version="1.0" encoding="utf-8"?>' +
17  '<note importance="high" logged="true">' +
18  '    <title>Happy</title>' +
19  '    <todo>Work</todo>' +
20  '    <todo>Play</todo>' +
21  '</note>';
22let conv = new convertxml.ConvertXML();
23// 转换选项, 参考文档使用
24let options = {
25  trim: false,
26  declarationKey: "_declaration",
27  instructionKey: "_instruction",
28  attributesKey: "_attributes",
29  textKey: "_text",
30  cdataKey: "_cdata",
31  doctypeKey: "_doctype",
32  commentKey: "_comment",
33  parentKey: "_parent",
34  typeKey: "_type",
35  nameKey: "_name",
36  elementsKey: "_elements"
37}
38let result: any = conv.convert(xml, options) // 将xml文本转为JS对象
39console.log('Test: ' + JSON.stringify(result))
40console.log('Test: ' + result._declaration._attributes.version) // xml字符串中version字段信息
41console.log('Test: ' + result._elements[0]._elements[0]._elements[0]._text) // xml字符串中title字段内容
42```
43
44参考文档:[xml转换JavaScript](../reference/apis/js-apis-convertxml.md)
45
46## 如何将时间转为时分秒格式
47
48示例:
49
50
51```
52export default class DateTimeUtil{
53  /**
54  * 时分秒
55  */
56  getTime() {
57    const DATETIME = new Date()
58    return this.concatTime(DATETIME.getHours(),DATETIME.getMinutes(),DATETIME.getSeconds())
59  }
60  /**
61  * 年月日
62  */
63  getDate() {
64    const DATETIME = new Date()
65    return this.concatDate(DATETIME.getFullYear(),DATETIME.getMonth()+1,DATETIME.getDate())
66  }
67  /**
68  * 日期不足两位补充0
69  * @param value-数据值
70  */
71  fill(value:number) {
72    return (value> 9 ? '' : '0') + value
73  }
74  /**
75  * 年月日格式修饰
76  * @param year
77  * @param month
78  * @param date
79  */
80  concatDate(year: number, month: number, date: number){
81    return `${year}${this.fill(month)}${this.fill(date)}`
82  }
83  /**
84  * 时分秒格式修饰
85  * @param hours
86  * @param minutes
87  * @param seconds
88  */
89  concatTime(hours:number,minutes:number,seconds:number){
90    return `${this.fill(hours)}${this.fill(minutes)}${this.fill(seconds)}`
91  }
92}
93
94```
95
96