1

I have a very complex XML tree, which has several namespaces in schema. I managed to generate corresponding Jaxb (using eclipse IDE) and marshaller/unmarshaller works fine.

Now, I want the XML into specific format, because i need to feed it to some system, and I have no other option.

The generated XML is:

    <?xml version="1.0" encoding="UTF-8" standalone="no"?>
    <ns2:data xmlns:ns2="ns:example-main" xmlns:ns10="ns:example-main/mynamespace10"        xmlns:ns11="http://www.w3.org/1999/XSL/Transform"  xmlns:ns4="ns:example-main/mynamespace5" xmlns:ns5="ns:example-main/mynamespace6" xmlns:ns6="ns:example-main/mynamespace111" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="ns:example-main resource:example-main">
<ns6:ruleList>
<ns6:rule>
<ns6:name>DFAC</ns6:name>
<ns6:className>com.example.Rule</ns6:className>
<ns6:label>DFAC class</ns6:label>
</ns6:rule>
</ns6:ruleList>
</ns2:data>

XML I need to generate

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<data xmlns="ns:example-main" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="ns:example-main resource:example-main">
<ruleList xmlns="ns:example-main/Rule" xsi:schemaLocation="ns:example-main/Rule resource:Rule">
<rule>
<name>DFAC</name>
<className>com.example.Rule</className>
<label>DFAC class</label>
</rule>
</ruleList>
</data>

I'm using Jaxb RI 2.2.6 What I have done so far: 1.

myjaxbMarshaller.setProperty("com.sun.xml.bind.namespacePrefixMapper", new MyNamespaceMapper());

and return "" from method

  1. @XmlSchema annotation with xmlns

    @XmlSchema(namespace="example-main",xmlns={@javax.xml.bind.annotation.XmlNs(namespaceURI="ns:example-main", prefix=""))

  2. writing into DOM tree and using dom's namespace configurations and then marsahlling dom:

    doc.getDomConfig().setParameter("namespaces", true); doc.getDomConfig().setParameter("namespace-declarations", true); doc.normalizeDocument();

or seting namespaces to false in above lines, to completely get rid of namespace, but it doesn't help either

4

1 回答 1

0

您可以尝试使用NamespacePrefixMapper. 您必须扩展它并将其设置为属性。

这是最短方法的示例:

marshaller.setProperty("com.sun.xml.bind.namespacePrefixMapper", 
                                              new NamespacePrefixMapper() {

            @Override
            public String[] getPreDeclaredNamespaceUris() {
                return new String[] { MyNamespaces.EXAMPLE_MAIN };
            }

            @Override
            public String getPreferredPrefix(String namespaceUri, String suggestion, boolean requirePrefix) {
                if (namespaceUri.equals(MyNamespaces.EXAMPLE_MAIN) ||
                    namespaceUri.equals(MyNamespaces.EXAMPLE_MAIN_RULE))

                    return "";

            }
        }); 
于 2013-09-19T08:47:50.087 回答