spring-xom-unmarshaller
Spring XML Unmarshalling with XOM
Maven
<dependency>
<groupId>com.itelg.spring</groupId>
<artifactId>spring-xom-unmarshaller</artifactId>
<version>1.4.0</version>
</dependency>
Configuration
Enable auto-configuration via annotation
@Autowire XomUnmarshaller for further use in MarshallingHttpMessageConverter or MarshallingMessageConverter.
@SpringBootApplication
@EnableXomUnmarshaller
public class Application
{
@Autowired
private XomUnmarshaller xomUnmarshaller;
public static void main(String[] args) throws Exception
{
SpringApplication.run(Application.class, args);
}
}
Parser resolving
A matching parser can be resolved either via return-type, root-tag or an xpath-expression.
Root-tag resolving via return-type (Root-Tag: integer)
@Component
public class IntegerParser implements Parser<Integer>
{
@Override
public Integer parse(Element rootElement)
{
return XPathHelper.getInteger("data/@value", rootElement);
}
}
Root-tag resolving via annotation (Root-Tag: text, blob or string)
@Component
@RootTagMatcher("text")
@RootTagMatcher("blob")
public class TextParser implements Parser<String>
{
@Override
public Integer parse(Element rootElement)
{
return XPathHelper.getString("data/@value", rootElement);
}
}
Disable type-resolving via annotation (Root-Tag: text)
@Component
@RootTagMatcher("text")
@DisableRootTagTypeMatcher
public class TextParser implements Parser<String>
{
@Override
public Integer parse(Element rootElement)
{
return XPathHelper.getString("data/@value", rootElement);
}
}
Resolving via xpath-expression
@Component
@XPathExpressionMatcher("//response/customer")
public class CustomerParser implements Parser<Customer>
{
@Override
public Customer parse(Element rootElement)
{
Customer customer = new Customer();
customer.setId(XPathHelper.getPLong("//response/customer/id", rootElement));
return customer;
}
}
Resolving via xpath-expression-value
@Component
@XPathExpressionMatcher(value = "//response/@type", expressionValue = "customer")
public class XPathExpressionValueCustomerParser implements Parser<Customer>
{
@Override
public Customer parse(Element rootElement)
{
Customer customer = new Customer();
customer.setId(XPathHelper.getPLong("//response/data/id", rootElement));
return customer;
}
}
Additional features
Pre-parse interceptor
If you have to work with invalid XML`s you can create an interceptor to remove invalid chars or to fix the structure.
@Bean
public XomUnmarshaller xomUnmarshaller(List<Parser<?>> parsers)
{
return new XomUnmarshaller(parsers, xmlChars ->
{
var xml = new String(xmlChars);
xml = xml.replace("", "");
xml = xml.replace("", "");
xml = xml.replace("�", "");
xml = xml.replace("", "");
return xml.getBytes();
});
}
Test-Support
Parser<?> parser = new IntegerParser();
Assert.assertTrue(XomUnmarshallerTestUtil.resolves(parser, "<integer><data value=\"11\" /></integer>"));
Build & Release
Build
mvn clean package
Release
mvn clean deploy