### JavaScript CommonJS Usage with PartialXMLStreamParser Source: https://github.com/samhvw8/partial-xml-stream-parser/blob/main/README.md Provides an example of how to use the PartialXMLStreamParser in a JavaScript environment using CommonJS modules. It demonstrates initializing the parser with custom options, such as `textNodeName` and `attributeNamePrefix`. ```javascript const { PartialXMLStreamParser, xmlObjectToString } = require("partial-xml-stream-parser"); const parser = new PartialXMLStreamParser({ textNodeName: "#text", // Default is "#text" attributeNamePrefix: "@", // Default is "@" alwaysCreateTextNode: true, // Default is true // parsePrimitives: false, // Default is false // stopNodes: [], // Default is empty // maxDepth: null, // Default is null (no depth limit) // allowedRootNodes: [], // Default is empty (parse all XML unconditionally) }); ``` -------------------------------- ### Serialize XML Object to String in JavaScript Source: https://github.com/samhvw8/partial-xml-stream-parser/blob/main/README.md Demonstrates XML serialization from JavaScript objects to XML strings using xmlObjectToString. Includes examples of basic serialization, round-trip parsing, and CDATA handling for content with special characters. Dependencies: 'partial-xml-stream-parser'. ```javascript const { PartialXMLStreamParser, xmlObjectToString } = require("partial-xml-stream-parser"); // Example 1: Basic serialization const xmlObject = { document: { "@version": "1.0", header: { title: "Test Document" }, body: { section: [ { "@id": "s1", p: "Paragraph 1" }, { "@id": "s2", p: "Paragraph 2 with chars" } ] } } }; const xmlString = xmlObjectToString(xmlObject); console.log(xmlString); // Example 2: Round-trip parsing const parser = new PartialXMLStreamParser({ textNodeName: "#text", attributeNamePrefix: "@" }); // Parse the serialized XML back const parsed = parser.parseStream(xmlString); console.log(JSON.stringify(parsed.xml[0], null, 2)); // Serialize again - should be identical to original const reserialized = xmlObjectToString(parsed.xml[0]); console.log("Round-trip successful:", xmlString === reserialized); // Example 3: CDATA handling const textWithXml = "This contains and & entities"; const simpleObject = { message: textWithXml }; const serialized = xmlObjectToString(simpleObject); console.log(serialized); // Parse it back const reparsed = parser.parseStream(serialized); console.log(reparsed.xml[0].message["#text"]); ``` -------------------------------- ### Configure Text Node Creation with `alwaysCreateTextNode` Source: https://github.com/samhvw8/partial-xml-stream-parser/blob/main/README.md Explains the `alwaysCreateTextNode` option in `PartialXMLStreamParser`. When true (default), text content is consistently placed in a specified text node. When false, text-only elements are simplified, which is shown in an example. ```javascript // Example with alwaysCreateTextNode: false (NOT THE DEFAULT) const parserOldBehavior = new PartialXMLStreamParser({ alwaysCreateTextNode: false, textNodeName: "#text", }); const resultOld = parserOldBehavior.parseStream("text"); console.log(JSON.stringify(resultOld, null, 2)); // Output (if alwaysCreateTextNode were false): // { // "metadata": { "partial": false }, // "xml": [ { "root": { "item": "text" } } ] // } // Default behavior (alwaysCreateTextNode: true): const parserDefault = new PartialXMLStreamParser({ textNodeName: "#myText" }); const resultDefault = parserDefault.parseStream("text"); console.log(JSON.stringify(resultDefault, null, 2)); // Output (default behavior): // { // "metadata": { "partial": false }, // "xml": [ { "root": { "item": { "#myText": "text" } } } ] // } ``` -------------------------------- ### Initialize PartialXMLStreamParser with Options Source: https://context7.com/samhvw8/partial-xml-stream-parser/llms.txt Demonstrates how to initialize the PartialXMLStreamParser with default and custom options. Options include text node naming, attribute prefixes, stop nodes, max depth, and allowed root nodes. This constructor provides full type safety with TypeScript. ```typescript import { PartialXMLStreamParser, ParserOptions } from "partial-xml-stream-parser"; // Basic usage with default options const parser1 = new PartialXMLStreamParser(); // Full configuration with all options const options: ParserOptions = { textNodeName: "#text", // Name for text content nodes (default: "#text") attributeNamePrefix: "@", // Prefix for XML attributes (default: "@") alwaysCreateTextNode: true, // Always wrap text in text nodes (default: true) parsePrimitives: false, // Convert strings to numbers/booleans (default: false) stopNodes: ["script", "style"], // Tags whose content won't be parsed maxDepth: 3, // Maximum parsing depth (default: null/unlimited) allowedRootNodes: ["message"], // Only parse these root elements (default: []/all) ignoreWhitespace: false // Ignore whitespace-only nodes (default: false) }; const parser2 = new PartialXMLStreamParser(options); // TypeScript provides full type safety const result = parser2.parseStream('Hello'); console.log(result.xml[0].message["@id"]); // "1" console.log(result.xml[0].message["#text"]); // "Hello" ``` -------------------------------- ### PartialXMLStreamParser Class Constructor Source: https://context7.com/samhvw8/partial-xml-stream-parser/llms.txt Initializes a new PartialXMLStreamParser instance with configurable options. This allows customization of text node names, attribute prefixes, stop nodes, maximum depth, and more. ```APIDOC ## PartialXMLStreamParser Class Constructor ### Description Initializes a new XML stream parser with configurable options for text node naming, attribute prefixes, stop nodes, depth limits, primitive parsing, and conditional root node filtering. ### Method ```typescript new PartialXMLStreamParser(options?: ParserOptions) ``` ### Parameters #### Constructor Options (`ParserOptions`) - **textNodeName** (string) - Optional - Name for text content nodes (default: "#text") - **attributeNamePrefix** (string) - Optional - Prefix for XML attributes (default: "@") - **alwaysCreateTextNode** (boolean) - Optional - Always wrap text in text nodes (default: true) - **parsePrimitives** (boolean) - Optional - Convert strings to numbers/booleans (default: false) - **stopNodes** (string[]) - Optional - Tags whose content won't be parsed - **maxDepth** (number | null) - Optional - Maximum parsing depth (default: null/unlimited) - **allowedRootNodes** (string[]) - Optional - Only parse these root elements (default: []/all) - **ignoreWhitespace** (boolean) - Optional - Ignore whitespace-only nodes (default: false) ### Request Example ```typescript import { PartialXMLStreamParser, ParserOptions } from "partial-xml-stream-parser"; // Basic usage with default options const parser1 = new PartialXMLStreamParser(); // Full configuration with all options const options: ParserOptions = { textNodeName: "#text", attributeNamePrefix: "@", alwaysCreateTextNode: true, parsePrimitives: false, stopNodes: ["script", "style"], maxDepth: 3, allowedRootNodes: ["message"], ignoreWhitespace: false }; const parser2 = new PartialXMLStreamParser(options); ``` ### Response #### Success Response A new instance of `PartialXMLStreamParser`. #### Response Example ```typescript // Example of parsing with the created parser const result = parser2.parseStream('Hello'); console.log(result.xml[0].message["@id"]); // "1" console.log(result.xml[0].message["#text"]); // "Hello" ``` ``` -------------------------------- ### Parse LLM Output with Mixed Content and Tool Calls (JavaScript) Source: https://github.com/samhvw8/partial-xml-stream-parser/blob/main/README.md Demonstrates parsing a simulated LLM response containing natural language and XML tool calls using PartialXMLStreamParser. It shows how to configure allowed root nodes and process the entire response at once. The output preserves both text and structured XML data. Input is a string, output is a JSON object. ```javascript const parser = new PartialXMLStreamParser({ allowedRootNodes: ["read_file", "write_to_file", "execute_command"] }); const llmResponse = "I'll help you with that task.\n\n" + "src/index.ts\n\n" + "Now let's modify the file:\n\n" + "src/index.ts\n" + "// Updated content\n" + "console.log(\"Hello world\");\n" + "2\n\n" + "Let's run the code:\n\n" + "node src/index.ts"; let result = parser.parseStream(llmResponse); console.log("--- Mixed Content with Tool Calls ---"); console.log(JSON.stringify(result, null, 2)); ``` -------------------------------- ### TypeScript Usage with PartialXMLStreamParser Source: https://github.com/samhvw8/partial-xml-stream-parser/blob/main/README.md Illustrates how to use the PartialXMLStreamParser in a TypeScript environment. It shows type-safe parser configuration using `ParserOptions` and demonstrates parsing XML content, accessing the result, and checking for partial parsing status. ```typescript import { PartialXMLStreamParser, xmlObjectToString, ParserOptions, ParseResult } from "partial-xml-stream-parser"; // Type-safe parser configuration const options: ParserOptions = { textNodeName: "#text", // Default is "#text" attributeNamePrefix: "@", // Default is "@" alwaysCreateTextNode: true, // Default is true parsePrimitives: false, // Default is false stopNodes: [], // Default is empty maxDepth: null, // Default is null (no depth limit) allowedRootNodes: [], // Default is empty (parse all XML unconditionally) }; const parser = new PartialXMLStreamParser(options); // Type-safe parsing with full intellisense const result: ParseResult = parser.parseStream('Test'); // TypeScript knows the structure of the result if (result.xml && result.xml.length > 0) { console.log("Parsed successfully:", result.xml[0]); console.log("Is partial:", result.metadata.partial); } ``` -------------------------------- ### Stream LLM Output with Mixed Content in Chunks (JavaScript) Source: https://github.com/samhvw8/partial-xml-stream-parser/blob/main/README.md Illustrates parsing LLM output with mixed content and tool calls by processing the input in sequential chunks. This approach is useful for real-time streaming scenarios. The parser maintains its state across chunks, ensuring accurate parsing even with fragmented input. Input is an array of strings and null, output is JSON objects. ```javascript const parser = new PartialXMLStreamParser({ allowedRootNodes: ["read_file", "write_to_file", "execute_command"] }); const chunks = [ "I'll help you with that task.\n\nsrc/index.ts\n\n", "Now let's modify the file:\n\n" ]; chunks.forEach((chunk, i) => { console.log(`Processing chunk ${i + 1}:`); const result = parser.parseStream(chunk); console.log(JSON.stringify(result, null, 2)); }); const finalResult = parser.parseStream(null); console.log("Final result:"); console.log(JSON.stringify(finalResult, null, 2)); ``` -------------------------------- ### Handling Plain Text Input with PartialXMLStreamParser (JavaScript) Source: https://github.com/samhvw8/partial-xml-stream-parser/blob/main/README.md Demonstrates how the PartialXMLStreamParser handles input streams that contain plain text, whitespace-only text, or empty strings. It shows how the parser preserves whitespace in plain text and its behavior with empty or whitespace-only inputs. ```javascript const parser = new PartialXMLStreamParser(); // Example 1: Input with non-whitespace text let result1 = parser.parseStream(" This is some plain text. "); console.log("--- Plain Text Input ---"); console.log(JSON.stringify(result1, null, 2)); result1 = parser.parseStream(null); // End stream console.log(JSON.stringify(result1, null, 2)); parser.reset(); // Example 2: Input with only whitespace let result2 = parser.parseStream(" \t \n "); console.log("--- Whitespace-Only Input ---"); console.log(JSON.stringify(result2, null, 2)); result2 = parser.parseStream(null); // End stream console.log(JSON.stringify(result2, null, 2)); parser.reset(); // Example 3: Empty string input let result3 = parser.parseStream(""); console.log("--- Empty String Input ---"); console.log(JSON.stringify(result3, null, 2)); result3 = parser.parseStream(null); // End stream console.log(JSON.stringify(result3, null, 2)); ``` -------------------------------- ### Parse Streaming LLM XML with JavaScript Source: https://github.com/samhvw8/partial-xml-stream-parser/blob/main/README.md Demonstrates how to use the PartialXMLStreamParser to process XML chunks as they arrive from an LLM. It simulates a stream, parses each chunk, and handles the final stream signal. The parser's default behavior (alwaysCreateTextNode: true) influences the structure of the parsed XML, creating '#text' nodes for element content and '@' attributes for XML attributes. ```javascript const llmStream = [ "thinking", 'First part of data...', 'Second part, still thinking...', ``` ```javascript " still processing...partial", "", // Let's imagine the stream ends here, maybe prematurely ]; const parser = new PartialXMLStreamParser(); // alwaysCreateTextNode is true by default llmStream.forEach((chunk) => { const result = parser.parseStream(chunk); if (result && result.xml && result.xml.length > 0) { console.log("--- Partial LLM XML ---"); console.log(JSON.stringify(result.xml, null, 2)); // Example access, assuming result.xml is an array with one root object // With alwaysCreateTextNode: true (default), structure is consistent: // responseObj.status will be { "#text": "thinking" } or { "#text": "partial" } // responseObj.data.item will be an array of objects like { "@id": "1", "#text": "..." } const responseObj = result.xml[0].response; if (responseObj && responseObj.data && responseObj.data.item) { const items = Array.isArray(responseObj.data.item) ? responseObj.data.item : [responseObj.data.item]; items.forEach((item) => { if (item["#text"] && item["#text"].includes("still processing...")) { console.log(`Item ${item["@id"]} is still processing.`); } }); } } }); const finalResult = parser.parseStream(null); // Signal end of stream console.log("--- Final LLM XML ---"); console.log(JSON.stringify(finalResult.xml, null, 2)); // Expected final output would show items with "#text" nodes, e.g., // "item": [ { "@id": "1", "#text": "First part of data..." }, { "@id": "2", "#text": "Second part, still thinking... still processing..." } ] // "status": [ { "#text": "thinking" }, { "#text": "partial" } ] ``` -------------------------------- ### Stream XML Data with parseStream Method Source: https://context7.com/samhvw8/partial-xml-stream-parser/llms.txt Illustrates the usage of the `parseStream` method for processing XML data in chunks. It shows how to handle partial XML data across multiple calls and how to signal the end of the stream. The `metadata.partial` property indicates if the parsing is complete. ```typescript import { PartialXMLStreamParser, ParseResult } from "partial-xml-stream-parser"; const parser = new PartialXMLStreamParser({ textNodeName: "#text" }); // Stream XML in multiple chunks let result: ParseResult = parser.parseStream('Te'); console.log(result); // Output: // { // metadata: { partial: true }, // xml: [{ root: { item: { "@id": "1", "#text": "Te" } } }] // } result = parser.parseStream('stValue'); console.log(result); // Output: // { // metadata: { partial: true }, // xml: [{ root: { item: [ // { "@id": "1", "#text": "Test" }, // { "@id": "2", "#text": "Value" } // ] } }] // } result = parser.parseStream(''); console.log(result); // Output: // { // metadata: { partial: false }, // xml: [{ root: { item: [ // { "@id": "1", "#text": "Test" }, // { "@id": "2", "#text": "Value" } // ] } }] // } // Signal end of stream with null result = parser.parseStream(null); console.log(result.metadata.partial); // false ``` -------------------------------- ### Configure Stop Nodes with Wildcard Patterns for Raw Text Handling Source: https://context7.com/samhvw8/partial-xml-stream-parser/llms.txt This feature allows defining specific XML tags whose content should be treated as raw text, preventing further parsing within those elements. It supports exact tag names, path-based matching, and glob-style wildcards (prefix `*` and suffix `*`) for flexible configuration. ```typescript import { PartialXMLStreamParser } from "partial-xml-stream-parser"; // Exact tag name matching const parser1 = new PartialXMLStreamParser({ stopNodes: ["script", "style"], textNodeName: "#text" }); let result = parser1.parseStream( '' ); console.log(result.xml[0].root.script["#text"]); // Output: if (x < y && z > 0) { alert("Hi"); } // Prefix wildcard: matches any child of 'app' const parser2 = new PartialXMLStreamParser({ stopNodes: ["app.*"], textNodeName: "#text" }); result = parser2.parseStream( 'not parsed' ); console.log(result.xml[0].root.app.config["#text"]); // Output: not parsed // Suffix wildcard: matches any path ending with 'suggest' const parser3 = new PartialXMLStreamParser({ stopNodes: ["*.suggest"], textNodeName: "#text" }); result = parser3.parseStream( '' ); console.log(result.xml[0].root.follow_up.suggest["#text"]); // Output: // Multiple wildcards and mixed patterns const parser4 = new PartialXMLStreamParser({ stopNodes: ["script", "app.*", "*.config.*"], textNodeName: "#text" }); ``` -------------------------------- ### Handle CDATA Content in StopNodes with PartialXMLStreamParser Source: https://github.com/samhvw8/partial-xml-stream-parser/blob/main/README.md Demonstrates how `PartialXMLStreamParser` correctly extracts content from CDATA sections within stop nodes, removing CDATA markers and preserving inner content. It also shows handling of CDATA spanning across tag boundaries. ```javascript const parser = new PartialXMLStreamParser({ stopNodes: ["script"], textNodeName: "#text" }); const input = ` `; const result = parser.parseStream(input); console.log(result.xml[0].root.script["#text"]); // Output: "\nif (x < y && z > 0) {\n alert(\"Hello !\");\n}\n" // Note: CDATA markers are removed, content is preserved // CDATA spanning across tag boundaries const parser2 = new PartialXMLStreamParser({ stopNodes: ["a.b"], textNodeName: "#text" }); const input2 = `]]>`; const result2 = parser2.parseStream(input2); console.log(result2.xml[0].a.b["#text"]); // Output: "content" // Note: The inside CDATA is treated as content, not as a closing tag ``` -------------------------------- ### Conditional XML Root Node Parsing with Allowed Root Elements Source: https://github.com/samhvw8/partial-xml-stream-parser/blob/main/README.md Demonstrates how to use the `allowedRootNodes` option to parse only XML with specific root elements. If the root element is not in the allowed list, the stream is treated as plain text. The parser handles partial streams and can be configured with an array of allowed strings or a single string. ```javascript const parserAllowed = new PartialXMLStreamParser({ allowedRootNodes: ["message"] }); let resultAllowed = parserAllowed.parseStream("Hello"); console.log("--- Allowed Root ---"); console.log(JSON.stringify(resultAllowed, null, 2)); resultAllowed = parserAllowed.parseStream(null); // End stream console.log(JSON.stringify(resultAllowed, null, 2)); const parserNotAllowed = new PartialXMLStreamParser({ allowedRootNodes: ["message"] }); let resultNotAllowed = parserNotAllowed.parseStream("Warning"); console.log("--- Not Allowed Root (treated as plain text) ---"); console.log(JSON.stringify(resultNotAllowed, null, 2)); resultNotAllowed = parserNotAllowed.parseStream(null); // End stream console.log(JSON.stringify(resultNotAllowed, null, 2)); const parserPlainText = new PartialXMLStreamParser({ allowedRootNodes: ["message"] }); let resultPlainText = parserPlainText.parseStream("This is just simple text."); console.log("--- Plain text with allowedRootNodes active ---"); console.log(JSON.stringify(resultPlainText, null, 2)); resultPlainText = parserPlainText.parseStream(null); // End stream console.log(JSON.stringify(resultPlainText, null, 2)); const parserDefaultBehavior = new PartialXMLStreamParser(); // or { allowedRootNodes: [] } let resultDefaultBehav = parserDefaultBehavior.parseStream("info"); console.log("--- Default (no allowedRootNodes restriction) ---"); console.log(JSON.stringify(resultDefaultBehav, null, 2)); resultDefaultBehav = parserDefaultBehavior.parseStream(null); console.log(JSON.stringify(resultDefaultBehav, null, 2)); ``` -------------------------------- ### Use Wildcard Patterns in Stop Nodes Source: https://github.com/samhvw8/partial-xml-stream-parser/blob/main/README.md Stop nodes can utilize glob-style wildcard patterns with asterisks (`*`) for flexible matching of tag paths. This allows for prefix, suffix, middle, and mixed pattern matching, offering more dynamic control over which elements are treated as raw text. ```javascript // Prefix matching: matches any child of 'app' const parser1 = new PartialXMLStreamParser({ stopNodes: ["app.*"], textNodeName: "#text", }); const result1 = parser1.parseStream( 'not parsed' ); console.log(JSON.stringify(result1, null, 2)); // Suffix matching: matches any path ending with 'suggest' const parser2 = new PartialXMLStreamParser({ stopNodes: ["*.suggest"], textNodeName: "#text", }); const result2 = parser2.parseStream( 'not parsed' ); console.log(JSON.stringify(result2, null, 2)); // Middle wildcards: matches paths like 'app.config.value', 'app.settings.value' const parser3 = new PartialXMLStreamParser({ stopNodes: ["app.*.value"], textNodeName: "#text", }); // Multiple wildcards: matches any path with 'config' in the middle const parser4 = new PartialXMLStreamParser({ stopNodes: ["*.config.*"], textNodeName: "#text", }); // Mixed patterns: combine wildcards with regular stopNodes const parser5 = new PartialXMLStreamParser({ stopNodes: ["script", "app.*", "*.config"], textNodeName: "#text", }); ``` -------------------------------- ### Parse Primitive Types with PartialXMLStreamParser Source: https://github.com/samhvw8/partial-xml-stream-parser/blob/main/README.md Illustrates the use of the `parsePrimitives` option in `PartialXMLStreamParser` to automatically convert string values representing numbers and booleans into their respective primitive types during parsing. ```javascript const parser = new PartialXMLStreamParser({ parsePrimitives: true, }); const result = parser.parseStream( "42true", ); console.log(JSON.stringify(result, null, 2)); // Output: // { // "metadata": { // "partial": false // }, // "xml": [ // { // "data": { // "number": { // "#text": 42 // alwaysCreateTextNode is true by default // }, // "boolean": { // "#text": true // alwaysCreateTextNode is true by default // } // } // } // ] // } ``` -------------------------------- ### Stream Parse XML in JavaScript Source: https://github.com/samhvw8/partial-xml-stream-parser/blob/main/README.md Parses XML streams incrementally using PartialXMLStreamParser. Handles partial XML data and signals the end of the stream. Outputs JSON representation of the parsed XML. Dependencies: 'partial-xml-stream-parser'. ```javascript import { PartialXMLStreamParser, xmlObjectToString } from "partial-xml-stream-parser"; const parser = new PartialXMLStreamParser({ textNodeName: "#text", attributeNamePrefix: "@", alwaysCreateTextNode: true, }); let result; result = parser.parseStream('Te'); console.log(JSON.stringify(result, null, 2)); result = parser.parseStream("st"); console.log(JSON.stringify(result, null, 2)); result = parser.parseStream(""); console.log(JSON.stringify(result, null, 2)); result = parser.parseStream(null); // Signal end of stream console.log(JSON.stringify(result, null, 2)); ``` -------------------------------- ### Reset XML Stream Parser State Source: https://context7.com/samhvw8/partial-xml-stream-parser/llms.txt The `reset` method allows clearing the internal state of the `PartialXMLStreamParser`, enabling it to process new and independent XML streams without retaining data from previous parsing operations. This is crucial for handling multiple documents sequentially within the same parser instance. ```typescript import { PartialXMLStreamParser } from "partial-xml-stream-parser"; const parser = new PartialXMLStreamParser(); // Parse first document parser.parseStream('Content'); let result = parser.parseStream(null); console.log(result.xml[0]); // { doc1: { "#text": "Content" } } // Reset parser for new document parser.reset(); // Parse second document with clean state parser.parseStream('New content'); result = parser.parseStream(null); console.log(result.xml[0]); // { doc2: { "#text": "New content" } } ``` -------------------------------- ### Serialize XML Object to String in TypeScript Source: https://github.com/samhvw8/partial-xml-stream-parser/blob/main/README.md Converts a type-safe TypeScript object structure into an XML string using xmlObjectToString. Supports automatic CDATA wrapping for special characters and attribute prefixes. Dependencies: 'partial-xml-stream-parser'. ```typescript import { PartialXMLStreamParser, xmlObjectToString } from "partial-xml-stream-parser"; // Type-safe XML object structure interface DocumentStructure { document: { "@version": string; header: { title: string }; body: { section: Array<{ "@id": string; p: string; }>; }; } } const xmlObject: DocumentStructure = { document: { "@version": "1.0", header: { title: "Test Document" }, body: { section: [ { "@id": "s1", p: "Paragraph 1" }, { "@id": "s2", p: "Paragraph 2 with chars" } ] } } }; const xmlString = xmlObjectToString(xmlObject); console.log(xmlString); ``` -------------------------------- ### Convert XML Objects to Strings with CDATA Wrapping Source: https://context7.com/samhvw8/partial-xml-stream-parser/llms.txt The `xmlObjectToString` function serializes JavaScript objects into XML strings. It automatically wraps content containing special characters (<, >, &) in CDATA sections to preserve the original data. This function supports custom configurations for text node names and attribute prefixes. ```typescript import { xmlObjectToString, PartialXMLStreamParser } from "partial-xml-stream-parser"; // Serialize simple object to XML const xmlObject = { document: { "@version": "1.0", header: { title: { "#text": "Test Document" } }, body: { section: [ { "@id": "s1", p: { "#text": "Paragraph 1" } }, { "@id": "s2", p: { "#text": "Content with & entities" } } ] } } }; const xmlString = xmlObjectToString(xmlObject); console.log(xmlString); // Output: //
Test Document

Paragraph 1

& entities]]>

// Round-trip parsing - parse, serialize, parse again const parser = new PartialXMLStreamParser({ textNodeName: "#text", attributeNamePrefix: "@" }); const parsed = parser.parseStream(xmlString); const reserialized = xmlObjectToString(parsed.xml[0]); console.log(xmlString === reserialized); // true - perfect round-trip // Custom options for serialization const customXml = xmlObjectToString(xmlObject, { textNodeName: "_text", attributeNamePrefix: "$" }); ``` -------------------------------- ### parseStream Method Source: https://context7.com/samhvw8/partial-xml-stream-parser/llms.txt Processes XML data incrementally in chunks, maintaining parser state across calls. This is ideal for handling large XML documents or data arriving over a network stream. ```APIDOC ## parseStream Method ### Description Process XML data in chunks, returning parsed results with partial state tracking for streaming scenarios. The method handles incomplete XML fragments and continues parsing when new chunks are provided. ### Method ```typescript parseStream(chunk: string | null | undefined): ParseResult ``` ### Parameters #### Path Parameters - **chunk** (string | null | undefined) - Required - A string containing a chunk of XML data, or `null`/`undefined` to signal the end of the stream. ### Request Example ```typescript import { PartialXMLStreamParser, ParseResult } from "partial-xml-stream-parser"; const parser = new PartialXMLStreamParser({ textNodeName: "#text" }); // Stream XML in multiple chunks let result: ParseResult = parser.parseStream('Te'); console.log(result); result = parser.parseStream('stValue'); console.log(result); result = parser.parseStream(''); console.log(result); // Signal end of stream with null result = parser.parseStream(null); console.log(result.metadata.partial); // false ``` ### Response #### Success Response (200) - **xml** (Array) - An array representing the parsed XML structure. For streaming, this may contain partially parsed data until the stream ends. - **metadata** (object) - Contains metadata about the parsing process. - **partial** (boolean) - `true` if the parsing is incomplete (more data expected), `false` otherwise. #### Response Example ```json { "metadata": { "partial": true }, "xml": [ { "root": { "item": [ { "@id": "1", "#text": "Test" }, { "@id": "2", "#text": "Value" } ] } } ] } ``` ``` -------------------------------- ### Process Mixed XML and Text Streams in TypeScript Source: https://context7.com/samhvw8/partial-xml-stream-parser/llms.txt Parses a string containing both plain text and XML elements, extracting structured data. It's configured to allow specific root nodes for tool calls and defines a name for text nodes. The parser handles data streamed in chunks, including incomplete tags across boundaries. ```typescript import { PartialXMLStreamParser } from "partial-xml-stream-parser"; const parser = new PartialXMLStreamParser({ allowedRootNodes: ["read_file", "write_to_file", "execute_command"], textNodeName: "#text" }); const llmResponse = "I'll help you with that task.\n\n" + "src/index.ts\n\n" + "Now let's modify the file:\n\n" + "src/index.tsconsole.log(\"Hello\");\n\n" + "Let's run the code:\n\n" + "node src/index.ts"; const result = parser.parseStream(llmResponse); parser.parseStream(null); // Finalize console.log(result.xml); // Output: [ // "I'll help you with that task.\n\n", // { read_file: { path: { "#text": "src/index.ts" } } }, // "\n\nNow let's modify the file:\n\n", // { write_to_file: { // path: { "#text": "src/index.ts" }, // content: { "#text": "console.log(\"Hello\");" } // } }, // "\n\nLet's run the code:\n\n", // { execute_command: { command: { "#text": "node src/index.ts" } } } // ] // Stream in chunks parser.reset(); parser.parseStream("I'll help.\ntest.ts"); const finalResult = parser.parseStream(null); // Correctly handles partial tags across chunk boundaries ``` -------------------------------- ### TypeScript: Conditionally Parse XML Root Nodes Source: https://context7.com/samhvw8/partial-xml-stream-parser/llms.txt Configure the parser to only process specific root element names, treating all other content as plain text. This is useful for filtering streams and handling mixed content scenarios. Dependencies include the 'partial-xml-stream-parser' library. ```typescript import { PartialXMLStreamParser } from "partial-xml-stream-parser"; // Only parse XML with 'message' or 'notification' root elements const parser = new PartialXMLStreamParser({ allowedRootNodes: ["message", "notification"], textNodeName: "#text" }); // Allowed root - parsed as XML let result = parser.parseStream('Hello'); console.log(result.xml[0]); // Output: { message: { content: { "#text": "Hello" } } } parser.reset(); // Disallowed root - treated as plain text result = parser.parseStream('Warning'); console.log(result.xml); // Output: ["Warning"] parser.reset(); // Mixed content with allowed roots const mixedParser = new PartialXMLStreamParser({ allowedRootNodes: ["read_file", "write_file"], textNodeName: "#text" }); const llmOutput = "I'll read the file:\n" + "src/app.ts\n" + "And then write changes:\n" + "src/app.tsnew code"; result = mixedParser.parseStream(llmOutput); result = mixedParser.parseStream(null); console.log(result.xml); // Output: [ // "I'll read the file:\n", // { read_file: { path: { "#text": "src/app.ts" } } }, // "\nAnd then write changes:\n", // { write_file: { path: { "#text": "src/app.ts" }, content: { "#text": "new code" } } } // ] ``` -------------------------------- ### Control XML Parsing Depth Source: https://context7.com/samhvw8/partial-xml-stream-parser/llms.txt The `maxDepth` option limits the nesting level of XML elements that are parsed into objects. Elements beyond the specified maximum depth are treated as raw text, which is useful for preventing excessive memory consumption or potential denial-of-service attacks from deeply nested XML structures. ```typescript import { PartialXMLStreamParser } from "partial-xml-stream-parser"; // Allow depths 0, 1, and 2 (root + 2 levels) const parser = new PartialXMLStreamParser({ maxDepth: 2, textNodeName: "#text" }); const result = parser.parseStream( 'deep content' ); console.log(JSON.stringify(result.xml, null, 2)); // Output: // [ // { // "root": { // depth 0 - parsed // "level1": { // depth 1 - parsed // "level2": { // depth 2 - parsed // "#text": "deep content" // depth 3+ - raw text // } // } // } // } // ] // Practical use case: prevent malicious deep nesting const secureParser = new PartialXMLStreamParser({ maxDepth: 5, textNodeName: "#text" }); const untrustedXml = 'very deep'; const secureResult = secureParser.parseStream(untrustedXml); // Content beyond depth 5 becomes raw text, preventing stack overflow ``` -------------------------------- ### TypeScript: Decode XML Entities Source: https://context7.com/samhvw8/partial-xml-stream-parser/llms.txt Automatically decode XML entities (named, decimal, and hexadecimal) in text content and attributes. This ensures that characters like '<', '>', '&', and quotes are correctly represented in the parsed output. The 'textNodeName' and 'attributeNamePrefix' options are configurable. ```typescript import { PartialXMLStreamParser } from "partial-xml-stream-parser"; const parser = new PartialXMLStreamParser({ textNodeName: "#text", attributeNamePrefix: "@" }); // Named entities let result = parser.parseStream('Hello <world> & "test" 'value''); console.log(result.xml[0].doc["#text"]); // Output: Hello & "test" 'value' // Numeric entities (decimal and hex) result = parser.parseStream('<Hello& World>'); console.log(result.xml[0].doc["#text"]); // Output: // Entities in attributes result = parser.parseStream(''); console.log(result.xml[0].doc["@value"]); // Output: & "quoted" ``` -------------------------------- ### TypeScript: Parse XML to Primitive Types Source: https://context7.com/samhvw8/partial-xml-stream-parser/llms.txt Automatically convert string values to their appropriate primitive types (numbers, booleans) when parsing XML. This feature simplifies data handling by performing type coercion. Ensure 'parsePrimitives' is set to true in the parser options. ```typescript import { PartialXMLStreamParser } from "partial-xml-stream-parser"; const parser = new PartialXMLStreamParser({ parsePrimitives: true, textNodeName: "#text" }); const result = parser.parseStream( '4219.99trueTest' ); console.log(result.xml[0].data); // Output: // { // count: { "#text": 42 }, // number // price: { "#text": 19.99 }, // number // active: { "#text": true }, // boolean // name: { "#text": "Test" } // string (not convertible) // } // Without parsePrimitives (default behavior) const defaultParser = new PartialXMLStreamParser({ textNodeName: "#text" }); const defaultResult = defaultParser.parseStream('42'); console.log(defaultResult.xml[0].data.count); // Output: { "#text": "42" } // remains string ``` -------------------------------- ### Control XML Parsing Depth with maxDepth Source: https://github.com/samhvw8/partial-xml-stream-parser/blob/main/README.md The `maxDepth` option limits the nesting level of XML parsing. Tags beyond the specified depth are treated as stop nodes, preserving their content as raw text. This is useful for preventing excessive nesting, optimizing performance, and preserving content. ```javascript const parser = new PartialXMLStreamParser({ maxDepth: 2, // Allow depths 0, 1, and 2 - treat depth 3+ as text textNodeName: "#text", }); const result = parser.parseStream( 'deep content', ); console.log(JSON.stringify(result, null, 2)); ``` -------------------------------- ### Define Stop Nodes for Raw Text Content Source: https://github.com/samhvw8/partial-xml-stream-parser/blob/main/README.md The `stopNodes` option prevents the parser from processing the content of specified tags, treating it as raw text instead. This can be configured with exact tag names or flexible wildcard patterns. It's useful for handling specific elements like scripts or styles. ```javascript const parser = new PartialXMLStreamParser({ stopNodes: ["script", "style"], // Don't parse content inside script or style tags }); const result = parser.parseStream( '', ); console.log(JSON.stringify(result, null, 2)); ``` -------------------------------- ### TypeScript: Handle CDATA in Stop Nodes Source: https://context7.com/samhvw8/partial-xml-stream-parser/llms.txt Process CDATA sections within designated 'stop' nodes by extracting their content and removing CDATA markers. This is crucial for handling embedded scripts or complex text blocks within specific XML elements. The 'stopNodes' option specifies which elements should have their CDATA content extracted. ```typescript import { PartialXMLStreamParser } from "partial-xml-stream-parser"; const parser = new PartialXMLStreamParser({ stopNodes: ["script"], textNodeName: "#text" }); // CDATA content in stopnode is extracted const input = ` `; const result = parser.parseStream(input); console.log(result.xml[0].root.script["#text"]); // Output: // // if (x < y && z > 0) { // alert("Hello !"); // } // // (CDATA markers removed, content preserved) // CDATA spanning across tag boundaries const parser2 = new PartialXMLStreamParser({ stopNodes: ["code"], textNodeName: "#text" }); const input2 = ']]>'; const result2 = parser2.parseStream(input2); console.log(result2.xml[0].root.code["#text"]); // Output: content // (The inside CDATA is treated as content, not a closing tag) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.