JAXB编组问题 - 可能与命名空间有关

时间:2010-08-03 08:04:18

标签: java xml jaxb

给定初始XML(BPEL)文件:

 <?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>

我编写了一个使用JAXB的函数来修改XML中的一些数据。 功能如下:

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();
    }
}

与JAXB相关的编辑后得到的XML是:

<!-- 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>

不幸的是,生成的XML与我们的应用程序不兼容,因为我们的XML解析器在解析新XML时崩溃了。

所以:

  • 如何在生成的XML中删除命名空间ns0
  • 如何保留初始XML文件中的相同标题(缺少xml:xsd)?

谢谢!

1 个答案:

答案 0 :(得分:1)

如果您使用MOXy JAXB实施,则可以执行以下操作:

您的域名对象:

package example;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Process {

}

使用该包注释@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;

要使用MOXy JAXB,您需要使用以下条目在模型类中添加jaxb.properties文件:

javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory

这将生成XML:

<?xml version="1.0" encoding="UTF-8"?>
<process xmlns="http://www.example.org" xmlns:xsd="http://www.w3.org/2001/XMLSchema"/>