UNPKG

xml-parser.ts

Version:

A lightweight, zero-dependency XML parser for TypeScript/JavaScript that converts XML strings to JavaScript objects and vice versa.

137 lines (136 loc) 3.09 kB
/** * Parse XML string to javascript object. * * Supported: * - Nested elements * - Text content (as string or number) * - Multiple root elements * - CDATA * - Self-closing elements * * Ignored: * - Metadata * - Comments * * Not supported: * - Attributes * - Comments * - Element with both child elements and text content * - XML comments inside CDATA * * @description * - Nested elements are parsed as object properties using tag name as property name. * - Element with text content is parsed as string or number. * - Element appears multiple times is parsed as array. * * @example * XML content: * ```xml * <annotation> * <folder>images</folder> * <filename>maksssksksss0.png</filename> * <size> * <width>512</width> * <height>366</height> * </size> * <object> * <x>79</x> * <y>105</y> * </object> * <object> * <x>185</x> * <y>100</y> * </object> * </annotation> * ``` * * Parsed javascript object: * ```javascript * { * annotation: { * folder: "images", * filename: "maksssksksss0.png", * size: { * width: 512, * height: 366, * }, * object: [ * { x: 79, y: 105 }, * { x: 185, y: 100 } * ] * } * } * ``` */ export declare function xml_to_json(xml: string): { [k: string]: string | number | object; }; /** * Convert JavaScript object to XML string. * * @description * - Object properties become XML elements using property names as tag names. * - String and number values become text content. * - Arrays create multiple elements with the same tag name. * - Nested objects create nested XML elements. * - Empty objects create self-closing elements. * * @example * JavaScript object: * ```javascript * { * annotation: { * folder: "images", * filename: "maksssksksss0.png", * size: { * width: 512, * height: 366, * }, * object: [ * { x: 79, y: 105 }, * { x: 185, y: 100 } * ] * } * } * ``` * * Generated XML: * ```xml * <annotation> * <folder>images</folder> * <filename>maksssksksss0.png</filename> * <size> * <width>512</width> * <height>366</height> * </size> * <object> * <x>79</x> * <y>105</y> * </object> * <object> * <x>185</x> * <y>100</y> * </object> * </annotation> * ``` */ export declare function json_to_xml(object: Record<string, any>, options?: { /** default `''` */ initial_indent?: string; /** default `' '` (2 spaces) */ indent_step?: string; }): string; /** * @description Parse a single root element from XML string. * - Metadata and comments should be removed before passing to this function. */ export declare function parse_xml_element(xml: string, offset: number): { tag_name: string; properties: { [k: string]: string | number | object; }; text_content: string | null; offset: number; }; export declare function remove_xml_comments(xml: string): string; export declare function remove_xml_metadata(xml: string): string;