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.
- 🚀 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
- Installation
- Quick Start
- API Reference
- Examples
- POJO Requirements
- Supported Types
- Security
- Building
- Contributing
- License
- Clone the repository:
git clone https://github.com/kongsin/KXMLParser.git
cd KXMLParser- Build the project:
ant clean jar- Add the generated JAR to your classpath:
# Copy the JAR from build/ directory to your project
cp build/*.jar your-project/libs/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 .Copy the XMLParser.java file from src/com/kongsin/core/ to your project and ensure it's in the correct package structure.
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);Parses XML string into a Java object of the specified type.
Parameters:
xml: XML string to parsemodelClass: Target class type
Returns: Parsed object or null if parsing fails
Parses XML from a URL into a Java object.
Parameters:
url: URL pointing to XML resourcemodelClass: Target class type
Returns: Parsed object or null if parsing fails
Converts a Java object to XML string representation.
Parameters:
obj: Object to convert
Returns: XML string representation
Throws: IllegalAccessException if field access fails
// 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 Doepublic 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);
}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);try {
URL xmlUrl = new URL("https://example.com/data.xml");
Person person = parser.fromXml(xmlUrl, Person.class);
} catch (MalformedURLException e) {
// Handle URL parsing error
}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
}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
}KXMLParser automatically handles these Java types:
boolean,byte,short,int,long,float,doublechar
Boolean,Byte,Short,Integer,Long,Float,DoubleCharacter
String- Arrays of supported types
- Custom objects (nested)
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"]
}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
- Java 8 or higher
- Apache Ant (for automated building, optional)
# Clean and build
ant clean jar
# Compile only
ant compile
# Run tests (if available)
ant test
# Clean build artifacts
ant cleanIf 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 .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)
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
git clone https://github.com/kongsin/KXMLParser.git
cd KXMLParser
ant compileThis project is licensed under the MIT License - see the LICENSE file for details.
- 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