w

API Reference

This section provides technical details about the XML to JSON conversion process and programmatic usage.

Conversion Algorithm

XML Parsing Process

The XML to JSON converter uses a recursive parsing algorithm:

  1. Parse XML: Use browser's built-in DOMParser
  2. Validate Structure: Check for well-formed XML
  3. Traverse Elements: Recursively process each XML element
  4. Build JSON: Construct JSON object from XML structure
  5. Format Output: Apply pretty printing or compact formatting

Core Conversion Function

function xmlToJson(xml, includeAttributes) {
  const result = {};

  // Handle attributes
  if (includeAttributes && xml.attributes.length > 0) {
    result['@attributes'] = {};
    for (let i = 0; i < xml.attributes.length; i++) {
      const attr = xml.attributes[i];
      result['@attributes'][attr.name] = attr.value;
    }
  }

  // Handle child nodes
  const children = xml.childNodes;
  let hasTextContent = false;
  let textContent = '';

  for (let i = 0; i < children.length; i++) {
    const child = children[i];

    if (child.nodeType === Node.TEXT_NODE) {
      const text = child.textContent?.trim();
      if (text) {
        hasTextContent = true;
        textContent += text;
      }
    } else if (child.nodeType === Node.ELEMENT_NODE) {
      const childElement = child;
      const childName = childElement.tagName;

      if (!result[childName]) {
        result[childName] = [];
      }

      result[childName].push(xmlToJson(childElement, includeAttributes));
    }
  }

  // Add text content if present
  if (hasTextContent) {
    result['#text'] = textContent;
  }

  // Optimize single child elements
  const keys = Object.keys(result);
  if (keys.length === 1 && keys[0] !== '@attributes' && keys[0] !== '#text') {
    const childArray = result[keys[0]];
    if (Array.isArray(childArray) && childArray.length === 1) {
      return childArray[0];
    }
  }

  return result;
}

Data Structures

Input XML Structure

<root>
  <element attribute="value">Text content</element>
  <nested>
    <child>Child content</child>
  </nested>
</root>

Output JSON Structure

{
  "root": {
    "element": {
      "@attributes": {
        "attribute": "value"
      },
      "#text": "Text content"
    },
    "nested": {
      "child": "Child content"
    }
  }
}

Configuration Options

Conversion Settings

interface ConversionOptions {
  prettyPrint: boolean; // Format JSON with indentation
  includeAttributes: boolean; // Include XML attributes in output
}

History Record Structure

interface HistoryRecord {
  id: string; // Unique identifier
  inputXml: string; // Original XML content
  outputJson: string; // Converted JSON
  inputLength: number; // Length of input XML
  prettyPrint: boolean; // Pretty print setting used
  includeAttributes: boolean; // Attribute inclusion setting
  timestamp: number; // Conversion timestamp
}

Error Handling

XML Validation Errors

interface ValidationError {
  type: 'parse_error' | 'malformed_xml' | 'invalid_character';
  message: string;
  line?: number;
  column?: number;
}

Common Error Types

  • Parse Error: Malformed XML structure
  • Invalid Character: Unsupported characters in XML
  • Unclosed Tag: Missing closing tags
  • Invalid Attribute: Malformed attribute syntax

Browser Compatibility

Supported Browsers

  • Chrome: Version 60+
  • Firefox: Version 55+
  • Safari: Version 12+
  • Edge: Version 79+

Required APIs

  • DOMParser: For XML parsing
  • JSON.stringify: For JSON formatting
  • localStorage: For history persistence
  • Blob API: For file downloads

Performance Specifications

Processing Limits

  • Maximum XML Size: ~10MB (browser dependent)
  • Maximum Nesting Depth: ~1000 levels
  • Processing Time: <100ms for typical documents
  • Memory Usage: ~3x XML size during processing

Optimization Features

  • Lazy Parsing: Parse only when needed
  • Memory Management: Automatic cleanup of temporary objects
  • Efficient Traversal: Optimized DOM traversal algorithms
  • Caching: History caching for repeated conversions

Integration Examples

JavaScript Integration

// Basic usage
function convertXmlToJson(xmlString, options = {}) {
  const parser = new DOMParser();
  const xmlDoc = parser.parseFromString(xmlString, 'text/xml');

  // Check for parsing errors
  const parserError = xmlDoc.querySelector('parsererror');
  if (parserError) {
    throw new Error('Invalid XML format');
  }

  const jsonResult = xmlToJson(xmlDoc.documentElement, options.includeAttributes);

  if (options.prettyPrint) {
    return JSON.stringify(jsonResult, null, 2);
  } else {
    return JSON.stringify(jsonResult);
  }
}

// Usage example
try {
  const xmlData = '<root><item>value</item></root>';
  const jsonData = convertXmlToJson(xmlData, {
    prettyPrint: true,
    includeAttributes: true,
  });
  console.log(jsonData);
} catch (error) {
  console.error('Conversion failed:', error.message);
}

Vue.js Integration

<template>
  <div>
    <textarea v-model="xmlInput" @input="convertXml"></textarea>
    <textarea v-model="jsonOutput" readonly></textarea>
  </div>
</template>

<script setup>
import { ref, watch } from 'vue';

const xmlInput = ref('');
const jsonOutput = ref('');

const convertXml = () => {
  try {
    const result = convertXmlToJson(xmlInput.value, {
      prettyPrint: true,
      includeAttributes: true,
    });
    jsonOutput.value = result;
  } catch (error) {
    jsonOutput.value = `Error: ${error.message}`;
  }
};
</script>

React Integration

import React, { useState, useCallback } from 'react';

function XmlToJsonConverter() {
  const [xmlInput, setXmlInput] = useState('');
  const [jsonOutput, setJsonOutput] = useState('');

  const convertXml = useCallback(() => {
    try {
      const result = convertXmlToJson(xmlInput, {
        prettyPrint: true,
        includeAttributes: true,
      });
      setJsonOutput(result);
    } catch (error) {
      setJsonOutput(`Error: ${error.message}`);
    }
  }, [xmlInput]);

  return (
    <div>
      <textarea
        value={xmlInput}
        onChange={(e) => setXmlInput(e.target.value)}
        onInput={convertXml}
      />
      <textarea value={jsonOutput} readOnly />
    </div>
  );
}

Testing and Validation

Unit Testing

// Test cases for XML to JSON conversion
describe('XML to JSON Converter', () => {
  test('converts simple XML to JSON', () => {
    const xml = '<root><item>value</item></root>';
    const result = convertXmlToJson(xml);
    expect(result).toBe('{"root":{"item":"value"}}');
  });

  test('handles attributes correctly', () => {
    const xml = '<root id="1"><item>value</item></root>';
    const result = convertXmlToJson(xml, { includeAttributes: true });
    const parsed = JSON.parse(result);
    expect(parsed.root['@attributes'].id).toBe('1');
  });

  test('throws error for malformed XML', () => {
    const xml = '<root><item>value</root>';
    expect(() => convertXmlToJson(xml)).toThrow('Invalid XML format');
  });
});

Validation Functions

// XML validation
function isValidXml(xmlString) {
  try {
    const parser = new DOMParser();
    const xmlDoc = parser.parseFromString(xmlString, 'text/xml');
    const parserError = xmlDoc.querySelector('parsererror');
    return !parserError;
  } catch (error) {
    return false;
  }
}

// JSON validation
function isValidJson(jsonString) {
  try {
    JSON.parse(jsonString);
    return true;
  } catch (error) {
    return false;
  }
}

Troubleshooting

Common Issues

  1. Memory Issues: Large XML files may cause browser memory problems
  2. Performance: Complex XML structures may slow down conversion
  3. Encoding: Ensure proper UTF-8 encoding for international characters
  4. Browser Limits: Some browsers have stricter XML parsing limits

Debug Mode

// Enable debug logging
const DEBUG = true;

function convertXmlToJson(xml, options = {}) {
  if (DEBUG) {
    console.log('Converting XML:', xml.substring(0, 100) + '...');
    console.log('Options:', options);
  }

  // ... conversion logic

  if (DEBUG) {
    console.log('Conversion completed');
  }

  return result;
}
Was this page helpful?