Reputation: 12848
Given the intitial XML (BPEL) file:
<?xml version="1.0" encoding="UTF-8"?>
<process
name="TestSVG2"
xmlns="http://www.example.org"
targetNamespace="http://www.example.org"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<sequence>
<receive name="Receive1" createInstance="yes"/>
<assign name="Assign1"/>
<invoke name="Invoke1"/>
<assign name="Assign2"/>
<reply name="Reply1"/>
</sequence>
</process>
I have written a function that uses JAXB in order to modify some data inside the XML. The function is as follows:
public void editAction(String name, String newName) {
Process proc;
StringWriter sw = new StringWriter();
JAXBContext jaxbContext = null;
Unmarshaller unMarsh = null;
Object obj = new Object();
try {
/* XML TO JAVA OBJECT */
jaxbContext = JAXBContext.newInstance("org.example");
unMarsh = jaxbContext.createUnmarshaller();
obj = unMarsh.unmarshal(new File(path + "/resources/" + BPELFilename));
proc = (Process) obj;
Process.Sequence sequence = proc.getSequence();
/* Determine which element needs to be edited */
/* Do some editing , code wasn't included */
/* OBJ Back to XML */
Marshaller marsh = jaxbContext.createMarshaller();
marsh.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
//marsh.setProperty("com.sun.xml.bind.namespacePrefixMapper", new CustomPrefixMapper());
marsh.marshal(obj, new File(path + "/resources/" + BPELFilename));
} catch (JAXBException e) {
/* Be afraid */
e.printStackTrace();
}
}
The resulting XML after the JAXB-related editing is:
<!-- After -->
<?xml version="1.0" encoding="UTF-8"?>
<ns0:process
name="TestSVG2"
targetNamespace="http://www.example.org"
xmlns:ns0="http://www.example.org">
<ns0:sequence>
<ns0:receive name="newName" createInstance="yes"/>
<ns0:assign name="Assign1"/>
<ns0:assign name="Assign2"/>
<ns0:invoke name="Invoke1"/>
<ns0:reply name="Reply1"/>
</ns0:sequence>
</ns0:process>
Unfortunately the resulting XML, is not compliant to our application, as our XML parser crashes when is parsing the new XML.
So:
ns0
, in the resulting XML ?xml:xsd
is missing)?Thanks!
Upvotes: 1
Views: 5966
Reputation: 149047
If you use the MOXy JAXB implementation you can do the following:
Your domain objects:
package example;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class Process {
}
Use that package annotation @XmlSchema
@javax.xml.bind.annotation.XmlSchema(
namespace = "http://www.example.org",
xmlns = {
@javax.xml.bind.annotation.XmlNs(prefix = "xsd", namespaceURI = "http://www.w3.org/2001/XMLSchema"),
},
elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED)
package example;
To use MOXy JAXB you need to add a jaxb.properties file in with your model classes with the following entry:
javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory
This will produce the XML:
<?xml version="1.0" encoding="UTF-8"?>
<process xmlns="http://www.example.org" xmlns:xsd="http://www.w3.org/2001/XMLSchema"/>
Upvotes: 1