Java XML library. A really cool one. Obviously.

Overview

XMLBeam

This is a Java XML library with an extraordinary expressive API. By using XPath for read and write operations, many operations take only one line of Java code.
This is how it looks:

<xml>
   <example>
      <content type="foo" >bar</content>
   </example>
</xml>

Access XML content in an object oriented way:

public interface Example {
    
    // This is a getter for the attribute "type"
    @XBRead("/xml/example/content/@type")
    String getType();
    
    // This is a getter and a setter for the value of the element "content"
    @XBAuto("/xml/example/content")
    XBAutoValue<String> content();
}

Example example = new XBProjector().io().file("example.xml").read(Example.class);
String type = example.getType(); // "foo"
String content = example.content().get(); // "bar"
example.content().set("new value");

Or, direct access via XPath enabled collection types:

Map<String,String> map = new XBProjector().io().file("example.xml").readAsMapOf(String.class);
String type = map.get("/xml/example/content/@type");
String content = map.get("/xml/example/content");
map.put("/xml/example/content","new value");

Learn more on xmlbeam.org

Comments
  • XBWrite expression creates wrong result#2 'Root/Intermediate[X='Passed']'

    XBWrite expression creates wrong result#2 'Root/Intermediate[X='Passed']'

    Root/Intermediate[X='Passed'] creates

    <Root> <Intermediate>Value</Intermediate> </Root>

    instead of <Root> <Intermediate> <X>Passed</X> Value </Intermediate> </Root>

    bug 
    opened by SvenEwald 8
  • Pluggable XPath implementation

    Pluggable XPath implementation

    Congratulations to the elegant solution.

    May I please suggest though that the XPath implementation be abstracted and made plugable. The JDK implementation is not simply slow but horribly slow. The implementation I use is xjpath (http://commons.apache.org/proper/commons-jxpath/) and on my workloads it is approx. 40 times faster than JDK.

    Regards Nikolay

    documentation needed 
    opened by nikolayo 8
  • Accessing whitespace-only text nodes returns

    Accessing whitespace-only text nodes returns "null" in 1.4.20

    The behaviour of XMLBeam when accessing whitespace-only text nodes with text() has changed in 1.4.20.

    Sample test code:

    public class TextNodeTest {
    
        interface Item {
            @XBRead("/item/text()")
            String getText();
        }
    
        @Test
        public void testWhitespaceOnlyTextNode() {
            final Item item = new XBProjector().onXMLString("<item> </item>").createProjection(Item.class);
            assertEquals(" ", item.getText());
        }
    }
    

    With 1.4.19, item.getText() returns " " (single space), and the test succeeds. With 1.4.20, item.getText() returns null, and the test fails.

    The same can be reproduced for any text nodes that contain nothing but a non-empty sequence of whitespace characters like space, tab and newline.

    In our application, we can't change the XML, and we need to know precisely which text is present (even if it's only spaces). Is there any way with 1.4.20 to get the original contents of the part between <item> and </item>?

    bug 
    opened by robertgrabowski 7
  • Path with colon

    Path with colon

    @XBAuto("/r:xml/y:example/content") Hello: Does a path similar to this format support conversion? Does the path support special symbols? Thank。

    opened by PatientLiu 7
  • Optional as return type seems to be broken (JDK 8 + 9)

    Optional as return type seems to be broken (JDK 8 + 9)

    I am using xmlbeam 1.4.13 with the newest JDK 9.0.1. In my projection interface I have a method with return type Optional<String>. If I call this method, an IllegalArgumentException is raised (from line 362 in ProjectionInvocationHandler.ReadInvocationHandler).

    This is due to the control flow in that class: With the DefaultTypeConverter in use, an Optional return type is deemed unconvertable (isConvertable == false). Consequentially, lines 324-326 will not get executed, the lines that are supposed to deal with an Optional.

    My fix for now is to add an Optional conversion to the type converter:

    private static void fixOptionalTypeConversion(XBProjector projector) {
      DefaultTypeConverter typeConverter = projector.config().getTypeConverterAs(DefaultTypeConverter.class);
      typeConverter.setConversionForType(Optional.class, new DefaultTypeConverter.Conversion<>(null) {
        @Override
        public Optional convert(String data) {
          return Optional.ofNullable(data);
        }
      });
    }
    

    With that fix, the projection interface method returns an Optional as expected.

    Can you confirm this bug? I noticed the test repository for Java 8 having some tests for the Optional return type that pretty much resemble my situation.

    These tests fail if I run them against xmlbeam 1.4.13 (with JDKs 9.0.1 and 1.8.0_152). Are they still relevant and maintained? I noticed in the pom.xml that the project depends on xmlbeams 1.4.7-SNAPSHOT.

    bug 
    opened by ThomasGP 7
  • Allow projection interfaces to be non-public

    Allow projection interfaces to be non-public

    Currently projection interfaces need to be public (due to XBProjector.ensureIsValidProjectionInterface(…) explicitly checking). However, simply making the interface accessible should do the trick in such cases. In case that in turn throws an exception, a similar rejection exception could be raised.

    enhancement 
    opened by odrotbohm 5
  • Support format annotations for better parsing

    Support format annotations for better parsing

    For example, to parse a Date I need to register a Converter class.

    It would be slicker if I could put a @DateFormat("...some simpledateformat string...") annotation on the interface field, and XMLBeam would use that to parse the date.

    Same for ints, etc.

    enhancement 
    opened by neilmcguigan 5
  • Add support for String-based value objects

    Add support for String-based value objects

    Assume you read an XML document with the following element:

    <version>1.4.0.RELEASE</version>
    

    It would be cool if there was a way to parse the String value of the element into a value object directly:

    class ArtifactVersion {
    
      public ArtifactVersion(String source) { … }
      public static ArtifactVersion parse(String source) { … }
    }
    

    So assuming the value type adheres to a certain convention (a static factory method or a constructor taking a string - I'd slightly prefer the former), XmlBeam could return an instance of that type right from a projection:

    interface Pom {
    
      @XBRead("/version")
      ArtifactVersion getVersion();
    }
    

    On the writing side of things I guess simply calling toString() would do the trick as one can expect the String representation to be equal to the initially parsed format (see this blog for justification).

    enhancement 
    opened by odrotbohm 5
  • ProjectionFactory gone package protected in 1.4.11

    ProjectionFactory gone package protected in 1.4.11

    ProjectionFactory has been made package private in 1.4.11 which is a breaking API change and an unfortunate one as it's kind of neat to be able to only hold a reference to the factory rather than XBProjector. Was this by accident?

    I'll have to change Spring Data's XmlBeamHttpMessageConverter to make it compatible with the latest bugfix releases. Any chance you make this interface public again?

    bug 
    opened by odrotbohm 4
  • XBWrite expression not allowed #1: 'Root/Intermediate[X/Y='Passed']/Child'

    XBWrite expression not allowed #1: 'Root/Intermediate[X/Y='Passed']/Child'

    Same error as Root/Intermediate[X/Y='Passed']

    Relevant error message is: ... Caused by: org.xmlbeam.util.intern.duplex.XBXPathExprNotAllowedForWriting: Not expetced here.: Node PathExpr is not supported for writing expressions in line 1 col 18 to 21 ...

    bug 
    opened by SvenEwald 4
  • Unable to parse SOAP xml file

    Unable to parse SOAP xml file

    Hi !

    I inmediately fall in love with your project, and start using it to write/parse XML content in our application, but found one xml file that's blocking me completely, as i feel unable to make it worl.

    May i get some help from you ?

    <?xml version="1.0" encoding="UTF-8"?>
    <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <soap:Body><ns1:storeTokenResponse xmlns:ns1="http://recurring.services.adyen.com">
    <ns1:result><additionalData xmlns="http://recurring.services.adyen.com" xsi:nil="true" /><alias xmlns="http://recurring.services.adyen.com">B133243153928547</alias><aliasType xmlns="http://recurring.services.adyen.com">Default</aliasType><params xmlns="http://recurring.services.adyen.com" xsi:nil="true" /><pspEchoData xmlns="http://recurring.services.adyen.com" xsi:nil="true" /><pspReference xmlns="http://recurring.services.adyen.com">8514873382743402</pspReference><recurringDetailReference xmlns="http://recurring.services.adyen.com">8414873382748121</recurringDetailReference><redirectType xmlns="http://recurring.services.adyen.com" xsi:nil="true" /><redirectUrl xmlns="http://recurring.services.adyen.com" xsi:nil="true" /><result xmlns="http://recurring.services.adyen.com">Success</result></ns1:result></ns1:storeTokenResponse></soap:Body></soap:Envelope>
    

    This is the xml itself, as arrives from the network, but all i can get is to retrieve the Body tag. From there, everything is null.

    This is my Beam :

    public interface SOAPResponse {
    
        @XBRead("/soap:Envelope/soap:Body")
        Body getBody();
    
        interface Body {
            @XBRead("./ns1:storeTokenResponse/ns1:result")
            Result getResult();
        }
    
        interface Result {
    
            @XBRead("./ns1:alias")
            String getAlias();
    
            @XBRead("./ns1:aliasType")
            String getAliasType();
    
            @XBRead("./ns1:pspReference")
            String getPspReference();
    
            @XBRead("./ns1:recurringDetailReference")
            String getRecurringDetailReference();
    
            @XBRead("./ns1:result")
            String getResult();
    
        }
    }
    

    and this is my test-code

        @Test
        public void canParseXML() throws Exception{
    
            String content = new String(Files.readAllBytes(Paths.get("soap.xml")));
    
            SOAPResponse soapResponse = projector.onXMLString(content.trim())
                                                 .createProjection(SOAPResponse.class);
    
            Assert.assertNotNull(soapResponse.getBody());
    
            Result result = soapResponse.getBody().getResult();
    
            Assert.assertEquals("B133243153928547",result.getAlias());
            Assert.assertEquals("Default",result.getAliasType());
            Assert.assertEquals("8514873382743402",result.getPspReference());
            Assert.assertEquals("8414873382748121",result.getRecurringDetailReference());
            Assert.assertEquals("Success",result.getResult());
    
        }
    

    And yes, by using XPath online on the xml, the PspReference attributes is retrieved by using "ns1" prefix.

    Thanks a lot, i really appreciate your project.

    bug 
    opened by josetesan 4
  • Intermediate element not created when setting child projection

    Intermediate element not created when setting child projection

    I'm seeing an issue where when using @XBWrite the last element in the path isn't created.

    Here's a test case to explain what I mean.

    import static org.junit.Assert.assertEquals;
    
    import org.junit.Test;
    import org.xmlbeam.XBProjector;
    import org.xmlbeam.XBProjector.Flags;
    import org.xmlbeam.annotation.XBWrite;
    
    public class TestSetChildOnEmptyParent {
    
    	public interface Child {
    		@XBWrite("ChildData")
    		void setData(String data);
    	}
    	
    	public interface ParentWithRootElement {
    		@XBWrite("Root/ParentData")
    		void setData(String data);
    		
    		@XBWrite("Root/Child")
    		void setChild(Child child);
    	}
    
    	@Test
    	public void testSetChildProjectionEmptyParent() {
    		XBProjector projector = new XBProjector(Flags.TO_STRING_RENDERS_XML);
    		
    		ParentWithRootElement parent = projector.projectEmptyDocument(ParentWithRootElement.class);
    		
    		Child child = projector.projectEmptyDocument(Child.class);
    		child.setData("child data...");		
    		
    		parent.setChild(child);  
    		
    		System.out.println("Result: " + parent);
    		
    		// Doesn't generate <Child> intermediate level
    		assertEquals( 
    				  "<Root>\n"
    				+ "   <Child>\n"
    				+ "      <ChildData>child data...</ChildData>\n"
    				+ "   </Child>\n"
    				+ "</Root>",
    				parent.toString());
    	}
    	
    }
    opened by zhsc 1
  • ClassCastException when setting child projection on parent as document root

    ClassCastException when setting child projection on parent as document root

    I'm seeing this error while trying to set a child projection onto a parent projection where the @XBWrite segment is the document root.

    Here's a test case:

    
    import static org.junit.Assert.assertEquals;
    
    import org.junit.Test;
    import org.xmlbeam.XBProjector;
    import org.xmlbeam.XBProjector.Flags;
    import org.xmlbeam.annotation.XBWrite;
    
    public class TestSetChildUnderDocumentRoot {
    
    	public interface Child {
    		@XBWrite("ChildData")
    		void setData(String data);
    	}
    	
    	public interface ParentNoRootElement {
    
    		@XBWrite("Child")
    		void setChild(Child child);
    	}
    		
    	@Test
    	public void testSetChildOnParentAsDocumentRoot() {
    		XBProjector projector = new XBProjector(Flags.TO_STRING_RENDERS_XML);
    		
    		ParentNoRootElement parent = projector.projectEmptyDocument(ParentNoRootElement.class);
    		
    		Child child = projector.projectEmptyDocument(Child.class);
    		child.setData("child data...");
    		
    		parent.setChild(child);  
    		
    		/* Throws:
    		java.lang.ClassCastException: com.sun.org.apache.xerces.internal.dom.DocumentImpl cannot be cast to org.w3c.dom.Element
    			at org.xmlbeam.util.intern.DOMHelper.replaceElement(DOMHelper.java:511)
    			at org.xmlbeam.ProjectionInvocationHandler$WriteInvocationHandler.invokeProjection(ProjectionInvocationHandler.java:669)
    			at org.xmlbeam.ProjectionInvocationHandler$ProjectionMethodInvocationHandler.invoke(ProjectionInvocationHandler.java:206)
    			at org.xmlbeam.ProjectionInvocationHandler.invoke(ProjectionInvocationHandler.java:879)
    			at com.sun.proxy.$Proxy5.setChild(Unknown Source)
    		 */
    		
    		System.out.println("Result: " + parent);
    		
    		assertEquals(
    				  "<Child>\n"
    				+ "   <ChildData>child data...</ChildData>\n"
    				+ "</Child>",
    				parent.toString());
    	}
    }
    opened by zhsc 1
  • Support for JSON? (/o\ yeah, I know)

    Support for JSON? (/o\ yeah, I know)

    I just created an example and request for enhancement in Spring Framework to integrate XMLBeam with Spring MVC as it's uber useful in case you'd like to implement more lenient data binding from XML (as you might want to be able to adapt to slight document structure changes without changing consuming code.

    Thinking through this I wondered whether there's an opportunity to provide the data projecting approach to JSON documents, too, using JSONPath instead of XPath as JSON for better or for worse has become the lingua france of integration APIs. I know this might be a stretch but didn't actually imagine a better place to at least ask, as I think it would be well received.

    enhancement 
    opened by odrotbohm 4
Releases(1.4.24)
  • 1.4.24(Sep 4, 2022)

  • 1.4.23(Apr 17, 2022)

  • 1.4.22(Jan 18, 2022)

  • 1.4.21(Jan 15, 2022)

  • 1.4.20(Apr 12, 2021)

  • 1.4.19(Mar 31, 2021)

  • 1.4.18(Dec 11, 2020)

  • 1.4.17(Aug 11, 2020)

  • 1.4.16(Jun 7, 2018)

  • 1.4.15(Apr 15, 2018)

  • 1.4.14(Oct 31, 2017)

  • 1.4.13(Jul 25, 2017)

  • 1.4.12(Jun 17, 2017)

    • New AutoTypes allow now changing XML without projection interfaces.

    • New annotation @XBAuto unites setters & getters to one projection method.

    • Enhanced evaluation API allows in place changing of files.

    • New AutoMap type allows easy creation of documents from scratch.

    • Bug fixed: Default namespaces did not work when writing to the document root.

    Source code(tar.gz)
    Source code(zip)
  • 1.4.11(May 20, 2017)

  • 1.4.10(Feb 18, 2017)

  • 1.4.9(Oct 28, 2016)

    • Bug fixed: Check preventing nonpublic interfaces removed.
    • Enhancement: Extended existing exception feature to XBDelete & XBUpdate.
    • Bug fixed: Restructuring element lists in xml added empty lines in output document.
    Source code(tar.gz)
    Source code(zip)
  • 1.4.8(Mar 13, 2016)

  • 1.4.7(May 4, 2015)

    • Bug fixed: Projection interfaces could not use lambdas in default methods.
    • Bug fixed: XPath parameter names are not case sensitive any more.
    • Bug fixed: Fixed class loading issue when using xmlbeam.jar as OSGI bundle.
    • Enhancement: Now projection methods may declare Stream as return type.
    Source code(tar.gz)
    Source code(zip)
  • 1.4.6(Jan 12, 2015)

  • 1.4.5(Jan 4, 2015)

  • 1.4.4(Dec 14, 2014)

  • 1.4.3(Dec 8, 2014)

    • XMLBeam jars are now OSGI bundles, directly usable in eclipse target platform.
    • Source code is automatically attached in Eclipse RCP plugin development.
    • Nothing changes for non OSGI/RCP developers. The jars are just contain additional meta data.
    Source code(tar.gz)
    Source code(zip)
  • 1.4.2(Nov 24, 2014)

    • New feature: Specify a format pattern to choose the representation of dates and numbers. This works for reading and writing projection methods and can even be used in predicates.
    • XPath variables now provide a way to have dynamic projections without the need to recompile the XPath expression again. This is much faster when methods are reused with different parameters.
    Source code(tar.gz)
    Source code(zip)
  • 1.4.1(Nov 6, 2014)

    • New feature: Reading projection methods may now throw exceptions when values do not exist. Just declare your exception type in the method signature. If your exception constructor has parameters matching the projection methods, all method parameters are passed to the exception. This is useful if you call projection methods from multiple places and returning Optional would replicate your error handling.
    • Performance improvements.
    Source code(tar.gz)
    Source code(zip)
  • 1.4.0(Oct 13, 2014)

    • Changed the default value of String conversions to null. Now you get a null value on selecting non existing values. If you need the previous behavior, please instantiate the projector with the flag ABSENT_IS_EMPTY.
    • Replaced the old writing XPath logic with a new powerful parser with more features and better error diagnostics.
    • Removal of included ASM library. Default methods are handled via Reflection and MethodHandles now. Faster and 100kb smaller. ASM may come back to the project to replace the dynamic proxy. More benchmarking needed on this.
    Source code(tar.gz)
    Source code(zip)
  • 1.3.0(Sep 12, 2014)

    • Changed default value of Boolean, Float, Double, Interger, Long and Character to null. Now you get a null value on selecting non existing values of these types. Unfortunately this still does not work for String.
    • Support for java.util.Optional as return type.
    • Additional projection method checks. You may not use raw List or Optional types. You may not use Optional as a parameter type.
    • API-compatible with 1.2.x, but still a minor version increase because of library behavior change.
    Source code(tar.gz)
    Source code(zip)
  • 1.2.1(May 17, 2014)

    • New "update" mode for writing to the DOM tree. If no structure change is needed, use the annotation @XBUpdate providing full XPath capabilities.
    • Now int or Integer is allowed as return code for writing projection methods. Setters, deleters and updaters are going to return the number of changes made to the DOM tree.
    • URL protocol 'resouce://' now has a new abbreviation 'res://' to be compatible with org.apache.commons.vfs.
    • Minor bugfix with DOM-API integration. Just use org.w3c.dom.Node as return type or parameter anywhere.
    • API-compatible with 1.2.x
    Source code(tar.gz)
    Source code(zip)
  • 1.2.0(Apr 28, 2014)

  • 1.1.3(Apr 14, 2014)

    New Java 8 feature: Use method parameter names as XPath place holders!

        @XBRead("/{parentNode}/{subnode}[@id=''{id}'']")
        String readSomeValue(String parentNode,String subnode,int id);
    

    Of course, using the parameters ordinal number is still supported (and must be used with JDK6 & JDK7 ).

        @XBRead("/{0}/{1}[@id=''{2}'']")
        String readSomeValue(String parentNode,String subnode,int id);
    

    Notice: You have to use the javac option "-parameters" for your projection classes.

    Source code(tar.gz)
    Source code(zip)
    xmlprojector-1.1.3-javadoc.jar(383.63 KB)
    xmlprojector-1.1.3-sources.jar(175.17 KB)
    xmlprojector-1.1.3.jar(167.69 KB)
    xmlprojector-1.1.3.pom(6.47 KB)
icecream-java is a Java port of the icecream library for Python.

icecream-java is a Java port of the icecream library for Python.

Akshay Thakare 20 Apr 7, 2022
JPassport works like Java Native Access (JNA) but uses the Foreign Linker API instead of JNI. Similar to JNA, you declare a Java interface that is bound to the external C library using method names.

JPassport works like Java Native Access (JNA) but uses the Foreign Linker API instead of JNI. Similar to JNA, you declare a Java interface t

null 28 Dec 30, 2022
Java serialization library, proto compiler, code generator

A java serialization library with built-in support for forward-backward compatibility (schema evolution) and validation. efficient, both in speed and

protostuff 1.9k Dec 23, 2022
Discord IPC - Pure Java 16 library

Pure Java 16 library for interacting with locally running Discord instance without the use of JNI.

Meteor Development 8 Nov 14, 2022
A Local implementation of a java library functions to create a serverside and clientside application which will communicate over TCP using given port and ip address.

A Local implementation of java library functions to create a serverside and clientside application which will communicate over TCP using given port and ip address.

Isaac Barry 1 Feb 12, 2022
null 8 Dec 22, 2022
This library provides facilities to match an input string against a collection of regex patterns.

This library provides facilities to match an input string against a collection of regex patterns. This library acts as a wrapper around the popular Chimera library, which allows it to be used in Java.

Sahab 5 Oct 26, 2022
Apache OpenNLP library is a machine learning based toolkit for the processing of natural language text

Welcome to Apache OpenNLP! The Apache OpenNLP library is a machine learning based toolkit for the processing of natural language text. This toolkit is

The Apache Software Foundation 1.2k Dec 29, 2022
Scaffolding is a library for Minestom that allows you to load and place schematics.

This library is very early in development and has too many bugs to count. For your own safety, you should not use it in a production environment.

Crystal Games 18 Nov 29, 2022
Crackersanimator is a particle system library that works with the standard Android UI

Crackersanimator is a particle system library that works with the standard Android UI. This library build from https://github.com/plattysoft/Leonids library but make some update to support for latest version of android.

null 3 Jun 14, 2022
Modern Java - A Guide to Java 8

Modern Java - A Guide to Java 8 This article was originally posted on my blog. You should also read my Java 11 Tutorial (including new language and AP

Benjamin Winterberg 16.1k Jan 5, 2023
There are two versions of assignments(Java or C++) for the CS143-Compiler course, this repo is my Java-version solution.

Intro There are two versions of assignments(Java or C++) for the CS143-Compiler course, this repo is my Java-version solution. Course resources: This

F4DE 3 Dec 15, 2022
From Java To Kotlin - Your Cheat Sheet For Java To Kotlin

From Java To Kotlin From Java To Kotlin - Your Cheat Sheet For Java To Kotlin 中文支持 Português Español Print to Console Java System.out.print("Amit Shek

MindOrks 5.8k Dec 29, 2022
Ultra-fast SQL-like queries on Java collections

CQEngine - Collection Query Engine CQEngine – Collection Query Engine – is a high-performance Java collection which can be searched with SQL-like quer

Niall Gallagher 1.6k Dec 30, 2022
Design patterns implemented in Java

Design patterns implemented in Java Read in different language : CN, KR, FR, TR, AR Introduction Design patterns are the best formalized practices a p

Ilkka Seppälä 79k Dec 31, 2022
Feature Flags for Java made easy

✨ ✨ ✨ FF4J - Feature Flipping for Java ✨ ✨ ✨ FF4j, is an implementation of the Feature Toggle pattern. ?? Features Feature Toggle: Enable. and disable

FF4j 1.1k Dec 25, 2022
A Java to iOS Objective-C translation tool and runtime.

J2ObjC: Java to Objective-C Translator and Runtime Project site: https://j2objc.org J2ObjC blog: https://j2objc.blogspot.com Questions and discussion:

Google 5.9k Dec 29, 2022
Make Slack and Facebook Bots in Java.

JBot Make bots in Java. JBot is a java framework (inspired by Howdyai's Botkit) to make Slack and Facebook bots in minutes. It provides all the boiler

Ram 1.2k Dec 18, 2022
An in-memory file system for Java 7+

Jimfs Jimfs is an in-memory file system for Java 7 and above, implementing the java.nio.file abstract file system APIs. Getting started The latest rel

Google 2.2k Jan 3, 2023