Skip to content

kongsin/KXMLParser

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

53 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

KXMLParser

Java License

A lightweight, secure Java library for bidirectional XML-Object mapping using reflection. KXMLParser enables seamless conversion between XML documents and Java objects with built-in security features and support for complex data structures.

Features

  • 🚀 Bidirectional Mapping: Convert XML to Java objects and vice versa
  • 🔒 Security First: Built-in XXE (XML External Entity) protection
  • 📦 Type Support: Handles primitives, wrappers, arrays, and nested objects
  • 🌐 URL Support: Parse XML directly from URLs
  • Reflection-Based: No annotations or configuration required
  • 🛡️ Null Safety: Graceful handling of null values and missing elements

Table of Contents

Installation

From Source (Recommended)

  1. Clone the repository:
git clone https://github.com/kongsin/KXMLParser.git
cd KXMLParser
  1. Build the project:
ant clean jar
  1. Add the generated JAR to your classpath:
# Copy the JAR from build/ directory to your project
cp build/*.jar your-project/libs/

Manual Compilation

If Ant is not available, compile manually:

# Compile the core library
javac -d build/classes src/com/kongsin/core/XMLParser.java

# Create JAR file
jar -cvf KXMLParser.jar -C build/classes .

Manual Integration

Copy the XMLParser.java file from src/com/kongsin/core/ to your project and ensure it's in the correct package structure.

Quick Start

import com.kongsin.core.XMLParser;

// Create parser instance
XMLParser parser = new XMLParser();

// Parse XML to object
String xml = "<Person><name>John Doe</name><age>30</age></Person>";
Person person = parser.fromXml(xml, Person.class);

// Convert object to XML
String xmlOutput = parser.toXml(person);

API Reference

Core Methods

fromXml(String xml, Class<T> modelClass)

Parses XML string into a Java object of the specified type.

Parameters:

  • xml: XML string to parse
  • modelClass: Target class type

Returns: Parsed object or null if parsing fails

fromXml(URL url, Class<T> modelClass)

Parses XML from a URL into a Java object.

Parameters:

  • url: URL pointing to XML resource
  • modelClass: Target class type

Returns: Parsed object or null if parsing fails

toXml(Object obj)

Converts a Java object to XML string representation.

Parameters:

  • obj: Object to convert

Returns: XML string representation

Throws: IllegalAccessException if field access fails

Examples

Basic Object Mapping

// Define your POJO
public class Person {
    public String name;
    public int age;
    public String email;
    public boolean active;
}

// Usage
XMLParser parser = new XMLParser();

String xml = """
    <Person>
        <name>John Doe</name>
        <age>30</age>
        <email>john.doe@example.com</email>
        <active>true</active>
    </Person>
    """;

Person person = parser.fromXml(xml, Person.class);
System.out.println("Name: " + person.name); // Output: John Doe

Array Handling

public class Company {
    public String name;
    public String[] employees;
}

String xml = """
    <Company>
        <name>Tech Corp</name>
        <employees>
            <name>Alice</name>
            <name>Bob</name>
            <name>Charlie</name>
        </employees>
    </Company>
    """;

Company company = parser.fromXml(xml, Company.class);
for (String employee : company.employees) {
    System.out.println("Employee: " + employee);
}

Nested Objects

public class Address {
    public String street;
    public String city;
    public String zipCode;
}

public class Person {
    public String name;
    public Address address;
}

String xml = """
    <Person>
        <name>John Doe</name>
        <address>
            <street>123 Main St</street>
            <city>Anytown</city>
            <zipCode>12345</zipCode>
        </address>
    </Person>
    """;

Person person = parser.fromXml(xml, Person.class);

URL Parsing

try {
    URL xmlUrl = new URL("https://example.com/data.xml");
    Person person = parser.fromXml(xmlUrl, Person.class);
} catch (MalformedURLException e) {
    // Handle URL parsing error
}

Object to XML Conversion

Person person = new Person();
person.name = "Jane Smith";
person.age = 25;
person.email = "jane.smith@example.com";

try {
    String xml = parser.toXml(person);
    System.out.println(xml);
    /*
    Output:
    <Person>
    <name>Jane Smith</name>
    <age>25</age>
    <email>jane.smith@example.com</email>
    </Person>
    */
} catch (IllegalAccessException e) {
    // Handle conversion error
}

POJO Requirements

For optimal results, your Java classes should follow these guidelines:

  • Public Classes: Classes must be public
  • Public Fields: All fields should be public (parser uses reflection)
  • No-Arg Constructor: Classes need a public no-argument constructor
  • Field Naming: XML element names should match field names (case-sensitive)
  • Type Matching: Use appropriate Java types that match XML content
// ✅ Recommended
public class Product {
    public String name;
    public double price;
    public int quantity;
    public boolean inStock;
}

// ❌ Avoid
class Product {  // Package-private class
    private String name;  // Private fields
    // No default constructor
}

Supported Types

KXMLParser automatically handles these Java types:

Primitive Types

  • boolean, byte, short, int, long, float, double
  • char

Wrapper Types

  • Boolean, Byte, Short, Integer, Long, Float, Double
  • Character

Reference Types

  • String
  • Arrays of supported types
  • Custom objects (nested)

Array Support

Arrays are mapped from repeated XML elements:

<!-- XML -->
<person>
    <hobbies>reading</hobbies>
    <hobbies>swimming</hobbies>
    <hobbies>coding</hobbies>
</person>
// Maps to
public class Person {
    public String[] hobbies; // ["reading", "swimming", "coding"]
}

Security

KXMLParser includes built-in security features:

  • XXE Protection: Prevents XML External Entity attacks
  • Secure Parsing: Uses hardened DocumentBuilderFactory settings
  • Input Validation: Validates XML structure before processing

The parser automatically configures these security features:

  • Disables DOCTYPE declarations
  • Prevents external entity resolution
  • Blocks external DTD loading

Building

Prerequisites

  • Java 8 or higher
  • Apache Ant (for automated building, optional)

Build Commands (Ant)

# Clean and build
ant clean jar

# Compile only
ant compile

# Run tests (if available)
ant test

# Clean build artifacts
ant clean

Manual Build

If Ant is not available, use the provided build script:

# Make script executable (first time only)
chmod +x build.sh

# Build the project
./build.sh

# Or build manually
mkdir -p build/classes
javac -cp src -d build/classes src/com/kongsin/core/XMLParser.java
javac -cp build/classes:src -d build/classes src/com/kongsin/example/*.java
jar -cvf KXMLParser.jar -C build/classes .

Project Structure

KXMLParser/
├── src/
│   └── com/
│       └── kongsin/
│           └── core/
│               └── XMLParser.java
│           └── example/
│               ├── KXMLParserExample.java
│               ├── Person.java
│               └── Company.java
├── build.sh
├── build.xml
├── manifest.mf
├── nbproject/
├── README.md
├── LICENSE
└── KXMLParser.jar (generated)

Contributing

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

Development Setup

git clone https://github.com/kongsin/KXMLParser.git
cd KXMLParser
ant compile

License

This project is licensed under the MIT License - see the LICENSE file for details.

Acknowledgments

  • Built with Java's DOM parsing capabilities
  • Inspired by the need for simple, secure XML-Object mapping
  • Thanks to the Java community for reflection and XML processing APIs

Author: Kong Sin
Version: 2.0
Repository: https://github.com/kongsin/KXMLParser

About

The library for map XML to an Obect

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published