Skip to content

Commit 08f607f

Browse files
committed
feat: extend documentation of attribute parsing and support setting attributeNode while reading XML
1 parent aba0d26 commit 08f607f

File tree

1 file changed

+35
-3
lines changed

1 file changed

+35
-3
lines changed

packages/util/src/xml.ts

Lines changed: 35 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,24 @@ export interface XMLParseOptions {
4444
* @default false
4545
*/
4646
skipValidation?: boolean;
47+
/**
48+
* Defines the name of the node under which attributes in the JSON output are grouped.
49+
* The default is `$` for attributes groups.
50+
*
51+
* For example `{ attributeNode: '@attributes' }` with the following XML:
52+
* ```xml
53+
* <innerTag attr="value" />
54+
* ```
55+
* Will result in the following JSON:
56+
* ```json
57+
* "tag": {
58+
* "@attributes": {
59+
* "attr": "value"
60+
* }
61+
* }
62+
* ```
63+
*/
64+
attributeNode?: string;
4765
}
4866

4967
/**
@@ -74,8 +92,21 @@ export interface XMLStringfyOptions {
7492
*/
7593
stripEmptyNodes?: boolean;
7694
/**
77-
* Defines the prefix to use for attributes in the XML string.
78-
* The default is `@` for attributes groups.
95+
* Defines the name of the `node` to use for attributes in the XML string.
96+
* The default is `$` for attributes groups.
97+
*
98+
* For example `{ attributePrefix: '@attributes' }` with the following JSON:
99+
* ```json
100+
* "tag": {
101+
* "@attributes": {
102+
* "attr": "value"
103+
* }
104+
* }
105+
* ```
106+
* Will result in the following XML:
107+
* ```xml
108+
* <innerTag attr="value" />
109+
* ```
79110
*/
80111
attributePrefix?: string;
81112
}
@@ -156,6 +187,7 @@ export namespace XML {
156187

157188
const parserOptions : Partial<X2jOptions> = {
158189
...ParserDefaults,
190+
attributesGroupName: options.attributeNode ?? ParserDefaults.attributesGroupName,
159191
ignoreAttributes: options.ignoreAttributes ?? ParserDefaults.ignoreAttributes,
160192
trimValues: options.trimValues ?? ParserDefaults.trimValues,
161193
removeNSPrefix: options.ignoreNamespacePrefix ?? ParserDefaults.removeNSPrefix
@@ -209,7 +241,7 @@ export namespace XML {
209241

210242
const builderOptions: Partial<XmlBuilderOptions> = {
211243
format: !!indentBy,
212-
attributeNamePrefix: options?.attributePrefix ?? ParserDefaults.attributeNamePrefix,
244+
attributeNamePrefix: ParserDefaults.attributeNamePrefix,
213245
attributesGroupName: options?.attributePrefix ?? ParserDefaults.attributesGroupName,
214246
suppressEmptyNode: options?.stripEmptyNodes === true,
215247
indentBy

0 commit comments

Comments
 (0)