Home Ask Login Register

Developers Planet

Your answer is one click away!

user3218526 February 2016

JAXB with XPATH Flexibility to modify Objects at runtime

I want to modify JAXB loaded objects (from XML) so that i can marshall them back to the disk with updated XML.

Now lets take an example:

  <Customer id="1" name="Jack">
    <Address type="Residence">
      <FirstLine>1 saxon Court</FirstLine>
    <Customer id="2" name="Iain">
    <Address type="Residence">
      <FirstLine>104 Bank Road</FirstLine>

Now as I have multiple customers, I want to use XPATH functionality to get the handle of the Customer[@id=2] object where I can add/update an address. If I will not use the XPATH like functionality then JAXB generated classes will have "List customer" and I will have to iterate through the list of customer to match with my desirable Customer[@id=2].

Can anyone give me idea how to get the Object instance handle for the JAXB generated objects using XPATH, so I can marshall it back to update the actual XML on the disk. If it cannot be done through JAXB, then what can be alternative solution to read and write XMLs using java Objects with XPATH flexibility.

Updated Question with Sample code:

Following is the sample code which shows what i want to achieve with Moxy/JAXB.

package org.soc.test.customers.moxy;

import java.io.File;
import java.util.List;
import javax.xml.bind.*;

public class UnmarshalDemo {
    public static void main(String[] args) throws Exception {
        org.eclipse.persistence.jaxb.JAXBContext jc =    (org.eclipse.persistence.jaxb.JAXBContext)     JAXBContext.newInstance(Customer.class);
        File instanceDoc = new File("input.xml");
        Customer customer = (Customer) jc.createUnmarshaller() .unmarshal(instanceDoc);
        List<PhoneNumber>  phones = jc.getValueByXPath(customer,        


ipsi February 2016

It's not supported with Moxy. The org.eclipse.persistence.internal.oxm.Context only supports numeric indexes in square brackets. While the XPathFragment understands it and creates appropriate predicates, the Context ignores those as far as searching for a match goes. I'd either raise a bug, or look for another tool.

See the Context source code (Commit 7cedaac6cdf9384ae9a06129d6f9abd607f9e3c4, Line 371 onwards) for exactly what's happening.

Post Status

Asked in February 2016
Viewed 1,149 times
Voted 13
Answered 1 times


Leave an answer

Quote of the day: live life