1# @ohos.convertxml (XML-to-JavaScript Conversion)
2
3The **convertxml** module provides APIs for converting XML text into JavaScript objects.
4
5> **NOTE**
6>
7> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version.
8
9
10## Modules to Import
11
12```ts
13import { convertxml } from '@kit.ArkTS';
14```
15
16## ConvertXML
17
18### fastConvertToJSObject<sup>14+</sup>
19
20fastConvertToJSObject(xml: string, options?: ConvertOptions) : Object
21
22Converts an XML text into a JavaScript object.
23
24> **NOTE**
25>
26> In Windows, a newline is usually represented by the carriage return (CR) followed by the line feed (LF). However, the object obtained by calling this API uses only the LF to indicate a new line.
27
28**Atomic service API**: This API can be used in atomic services since API version 14.
29
30**System capability**: SystemCapability.Utils.Lang
31
32**Parameters**
33
34| Name | Type                             | Mandatory| Description           |
35| ------- | --------------------------------- | ---- | --------------- |
36| xml     | string                            | Yes  | XML text to convert. If the XML text contains the ampersand (&), replace it with the entity reference **\&amp;**.|
37| options | [ConvertOptions](#convertoptions) | No  | Options for conversion. The default value is a **ConvertOptions** object, which consists of the default values of the attributes in the object.|
38
39**Return value**
40
41| Type  | Description                        |
42| ------ | ---------------------------- |
43| Object | JavaScript object.|
44
45**Error codes**
46
47For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Utils Error Codes](errorcode-utils.md).
48
49| ID| Error Message|
50| -------- | -------- |
51| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. |
52| 10200002 | Invalid xml string. |
53
54**Example**
55
56```ts
57try {
58  let xml =
59    '<?xml version="1.0" encoding="utf-8"?>' +
60    '<note importance="high" logged="true">' +
61    '   <title>Hello\r\nWorld</title>' +
62    '   <todo><![CDATA[Work\r\n]]></todo>' +
63    '</note>';
64  let conv = new convertxml.ConvertXML()
65  let options: convertxml.ConvertOptions = {
66    trim: false, declarationKey: "_declaration",
67    instructionKey: "_instruction", attributesKey: "_attributes",
68    textKey: "_text", cdataKey: "_cdata", doctypeKey: "_doctype",
69    commentKey: "_comment", parentKey: "_parent", typeKey: "_type",
70    nameKey: "_name", elementsKey: "_elements"
71  }
72  let result = JSON.stringify(conv.fastConvertToJSObject(xml, options));
73  console.log(result);
74} catch (e) {
75  console.log((e as Object).toString());
76}
77// Output (non-compact)
78// {"_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":"Hello\nWorld"}]},{"_type":"element","_name":"todo","_elements":[{"_type":"cdata","_cdata":"Work\n"}]}]}]}
79```
80
81### convertToJSObject<sup>(deprecated)</sup>
82
83convertToJSObject(xml: string, options?: ConvertOptions) : Object
84
85Converts an XML text into a JavaScript object.
86
87> **NOTE**
88>
89> This API is supported since API version 9 and deprecated since API version 14. You are advised to use [fastConvertToJSObject<sup>14+</sup>](#fastconverttojsobject14) instead.
90
91**Atomic service API**: This API can be used in atomic services since API version 11.
92
93**System capability**: SystemCapability.Utils.Lang
94
95**Parameters**
96
97| Name | Type                             | Mandatory| Description           |
98| ------- | --------------------------------- | ---- | --------------- |
99| xml     | string                            | Yes  | XML text to convert. If the XML text contains the ampersand (&), replace it with the entity reference **\&amp;**.|
100| options | [ConvertOptions](#convertoptions) | No  | Options for conversion. The default value is a **ConvertOptions** object, which consists of the default values of the attributes in the object.|
101
102**Return value**
103
104| Type  | Description                        |
105| ------ | ---------------------------- |
106| Object | JavaScript object.|
107
108**Error codes**
109
110For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Utils Error Codes](errorcode-utils.md).
111
112| ID| Error Message|
113| -------- | -------- |
114| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. |
115| 10200002 | Invalid xml string. |
116
117**Example**
118
119```ts
120try {
121  let xml =
122    '<?xml version="1.0" encoding="utf-8"?>' +
123      '<note importance="high" logged="true">' +
124      '    <title>Happy</title>' +
125      '    <todo>Work</todo>' +
126      '    <todo>Play</todo>' +
127      '</note>';
128  let conv = new convertxml.ConvertXML()
129  let options: convertxml.ConvertOptions = {
130    trim: false, declarationKey: "_declaration",
131    instructionKey: "_instruction", attributesKey: "_attributes",
132    textKey: "_text", cdataKey: "_cdata", doctypeKey: "_doctype",
133    commentKey: "_comment", parentKey: "_parent", typeKey: "_type",
134    nameKey: "_name", elementsKey: "_elements"
135  }
136  let result = JSON.stringify(conv.convertToJSObject(xml, options));
137  console.log(result);
138} catch (e) {
139  console.log((e as Object).toString());
140}
141// Output (non-compact)
142// {"_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"}]}]}]}
143```
144
145### convert<sup>(deprecated)</sup>
146
147convert(xml: string, options?: ConvertOptions) : Object
148
149Converts an XML text into a JavaScript object.
150
151> **NOTE**
152>
153> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [fastConvertToJSObject<sup>14+</sup>](#fastconverttojsobject14) instead.
154
155**System capability**: SystemCapability.Utils.Lang
156
157**Parameters**
158
159| Name | Type                             | Mandatory| Description           |
160| ------- | --------------------------------- | ---- | --------------- |
161| xml     | string                            | Yes  | XML text to convert.|
162| options | [ConvertOptions](#convertoptions) | No  | Options for conversion. The default value is a **ConvertOptions** object, which consists of the default values of the attributes in the object. |
163
164**Return value**
165
166| Type  | Description                        |
167| ------ | ---------------------------- |
168| Object | JavaScript object.|
169
170**Example**
171
172```ts
173let xml =
174  '<?xml version="1.0" encoding="utf-8"?>' +
175    '<note importance="high" logged="true">' +
176    '    <title>Happy</title>' +
177    '    <todo>Work</todo>' +
178    '    <todo>Play</todo>' +
179    '</note>';
180let conv = new convertxml.ConvertXML();
181let options: convertxml.ConvertOptions = {trim : false, declarationKey:"_declaration",
182  instructionKey : "_instruction", attributesKey : "_attributes",
183  textKey : "_text", cdataKey:"_cdata", doctypeKey : "_doctype",
184  commentKey : "_comment", parentKey : "_parent", typeKey : "_type",
185  nameKey : "_name", elementsKey : "_elements"}
186let result = JSON.stringify(conv.convert(xml, options));
187console.log(result);
188// Output (non-compact)
189// {"_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"}]}]}]}
190```
191
192## ConvertOptions
193
194Options for conversion.
195
196**Atomic service API**: This API can be used in atomic services since API version 11.
197
198**System capability**: SystemCapability.Utils.Lang
199
200| Name             | Type| Mandatory| Description                                                       |
201| ----------------- | -------- | ---- | ----------------------------------------------------------- |
202| trim              | boolean  | Yes  | Whether to trim the whitespace characters before and after the text.                |
203| ignoreDeclaration | boolean  | No  | Whether to ignore the XML declaration. The default value is **false**.                       |
204| ignoreInstruction | boolean  | No  | Whether to ignore the XML processing instruction. The default value is **false**.                     |
205| ignoreAttributes  | boolean  | No  | Whether to ignore the element's attribute information. The default value is **false**.                  |
206| ignoreComment     | boolean  | No  | Whether to ignore element comments. The default value is **false**.                        |
207| ignoreCDATA       | boolean  | No  | Whether to ignore the element's CDATA information. The default value is **false**.                       |
208| ignoreDoctype     | boolean  | No  | Whether to ignore the element's Doctype information. The default value is **false**.                     |
209| ignoreText        | boolean  | No  | Whether to ignore the element's text information. The default value is **false**.                        |
210| declarationKey    | string   | Yes  | Name of the attribute key for **declaration** in the output object.|
211| instructionKey    | string   | Yes  | Name of the attribute key for **instruction** in the output object.|
212| attributesKey     | string   | Yes  | Name of the attribute key for **attributes** in the output object.  |
213| textKey           | string   | Yes  | Name of the attribute key for **text** in the output object.              |
214| cdataKey          | string   | Yes  | Name of the attribute key for **cdata** in the output object.            |
215| doctypeKey        | string   | Yes  | Name of the attribute key for **doctype** in the output object.        |
216| commentKey        | string   | Yes  | Name of the attribute key for **comment** in the output object.        |
217| parentKey         | string   | Yes  | Name of the attribute key for **parent** in the output object.          |
218| typeKey           | string   | Yes  | Name of the attribute key for **type** in the output object.              |
219| nameKey           | string   | Yes  | Name of the attribute key for **name** in the output object.              |
220| elementsKey       | string   | Yes  | Name of the attribute key for **elements** in the output object.      |
221