[JAXB] @XmlAnyElement namespace

Mewel

Aktives Mitglied
Hallo,

folgende Situation: ich füge ein w3c.DOM-Element (mit Namespace ohne Prefix) in ein mit @XmlAnyElement annotiertes Objekt ein und machen dann ein Marshalling. Leider wird dabei automatisch ein Prefix angehängt + ein zusätzlicher Namespace generiert. Ich habe mal ein einfaches Beispielprogramm geschrieben was den Effekt zeigt.

Java:
public class JAXBNamespaceTest {

    private static JAXBContext jaxbContext;

    private static Marshaller marshaller;

    static {
        try {
            jaxbContext = JAXBContext.newInstance(TestJAXB.class);
            marshaller = jaxbContext.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        } catch (Exception exc) {
            exc.printStackTrace();
        }
    }
    
    public void nsTest() throws Exception {
        // create dom
        DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        org.w3c.dom.Document doc = builder.newDocument();
        org.w3c.dom.Element e = doc.createElement("dom");
        e.setAttribute("xmlns", "www.google.de");
        doc.appendChild(e);
        // print dom
        System.out.println("So möchte ich das haben, ein Element ohne Prefix mit Namespace Attribut");
        xmlOut(doc); // perfect - only one xmlns tag
        System.out.println();
        System.out.println();

        // create jaxb stuff
        TestJAXB testJAXB = new TestJAXB();
        testJAXB.desciption.any = e;
        System.out.println("Und hier mit Prefix 'dom' und extra Namespace 'xmlns:dom'");
        marshaller.marshal(testJAXB, System.out); // why dom:dom and xmlns:dom? 
    }

    @XmlRootElement(name="test")
    public static class TestJAXB {
        public DescriptionType desciption = new DescriptionType();
    }

    @XmlType(name = "descriptionType")
    public static class DescriptionType {
        @XmlAnyElement(lax = false)
        public Object any;
    }

    public static void xmlOut(org.w3c.dom.Document doc) throws Exception {
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        Source source = new DOMSource(doc);
        Result output = new StreamResult(System.out);
        transformer.transform(source, output);
    }

    public static void main(String[] args) throws Exception {
        JAXBNamespaceTest nsTest = new JAXBNamespaceTest();
        nsTest.nsTest();
    }
}

Also mein Ziel ist:
[XML]
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<test>
<desciption>
<dom xmlns="www.google.de"/>
</desciption>
</test>
[/XML]

Hat jemand eine Idee wie ich das erreichen kann?
 

eRaaaa

Top Contributor
Mhm, also viel habe ich mit JAXB bisher nicht gemacht und daher jetzt nur Halbwissen:

Hat jemand eine Idee wie ich das erreichen kann?

Probiere es mal bei dem DescriptionType so:

Java:
    @XmlType(name = "descriptionType")
    public static class DescriptionType {
        @XmlElement
        public Object dom;
    }

die eine Zeile muss dann natürlich entsprechend geändert werden
Java:
 testJAXB.desciption.dom = e;

allerdings sieht das irgendwie alles merkwürdig aus (zumindest für mich als Halbwissender :p)
 

Mewel

Aktives Mitglied
Vielen Dank, das funktioniert :).

Einziges Problem ist jetzt noch das die JAXB-Klassen mit XJC automatisch generiert werden. Muss ich mir das XJB-Binding nochmal anschauen ob ich da ansetzten kann.
 

Mewel

Aktives Mitglied
Geht leider doch nicht, das Problem mit @XmlElement ist, das der Name nicht vom DOM-Element kommt (doc.createElement("hier_muss_was_variables_stehen")), sondern durch die Klasse vorgegeben ist.
 

Mewel

Aktives Mitglied
Habe eine Lösung gefunden:

Code:
public class NamespaceFilter extends XMLFilterImpl {

    private String xmlns = "";

    @Override
    public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException {
        if(uri.equals(xmlns)) {
            super.startElement(uri, localName, localName, atts);
        } else {
            super.startElement(uri, localName, qName, atts);
        }
    }

    @Override
    public void startPrefixMapping(String prefix, String uri) throws SAXException {
        if(prefix == null || prefix.length() == 0) {
            xmlns = uri;
        }
    }

}

Und marshalling mit:
Code:
NamespaceFilter outFilter = new NamespaceFilter();
SAXHandler saxHandler = new SAXHandler();
outFilter.setContentHandler(saxHandler);
marshaller.marshal( your_jaxb_element, outFilter);
return saxHandler.getDocument()
 
Ähnliche Java Themen
  Titel Forum Antworten Datum
8u3631984 jaxb XML Mapper - Root Element mit Attribut XML & JSON 20
W jaxws jaxb wsdl Java-Klassen generieren und binding.xml verwenden XML & JSON 1
Rakshan Unmarshalling multiple namespaces with jaxb XML & JSON 0
B JAXB und HTML XML & JSON 1
E JAXB und java.nio.file.Path XML & JSON 4
W jaxb-api XML Feld nicht gesendet setzt das Defaultvalue nicht XML & JSON 3
S Muss ich bei JAXB immer noch eine zusaetzliche List-Wrapper Klasse erstellen wenn ich mehrere Objekte serialisieren will..? XML & JSON 1
S JAXB mit mehreren zusammenhängenden .xsd-Files XML & JSON 0
N JAXB: Überflüssiges Wrapper-Tag für Map-Einträge XML & JSON 0
D JAXB mit Map und Color XML & JSON 2
K JAXB-XML unvollständig XML & JSON 1
K JAXB Unmarshelling XML & JSON 1
E JAXB und abstrakte Klasse(n) XML & JSON 0
B JAXB - Unmarshal -> Kinder bekommen und die Kinder von den Kinder XML & JSON 7
B JAXB - Marshal ArrayList XML & JSON 2
B JAXB - java.util.Locale does not have a no-arg default constructor XML & JSON 2
B JAXB-Fehler bei REST-Api XML & JSON 0
M JAXB HashMap Dynamisches Laden XML & JSON 0
M JAXB @XMLID und @XMLIDREF, wie Daten hinzufügen XML & JSON 2
P JAXB-Problem XML & JSON 1
A JAXB: XMLMixed generieren XML & JSON 0
R [JAXB] XmlRootElement und XmlType gemeinsam nutzen XML & JSON 0
I XML to Object - Mapping mit JAXB 1.0 XML & JSON 1
L JAXB - Generischen Wert mit Liste belegen XML & JSON 1
M XML-Datei mit JAXB und 2 Namespaces XML & JSON 0
K JAXB Annotation @XMLRootElement vererben XML & JSON 0
F JAXB Unmarshal - Kein "default Constructor" XML & JSON 2
F.S.WhiTeY JAXB: Schema nicht "erben" XML & JSON 2
B JAXB - manuell Klassen aus xsd XML & JSON 3
S Jaxb Unmarshalling Problem XML & JSON 4
S JAXB - Any Elementliste - wie Werte verändern? XML & JSON 4
R JAXB: A cycle is detected in the object graph. This will cause infinitely deep XML XML & JSON 6
M JAXB versucht abstrakte Klasse zu erzeugen XML & JSON 7
M JAXB: automatisches Groß schreiben Property XML & JSON 9
C Projekt - JAXB, EMF oder doch DOM? XML & JSON 4
C JAXB: XML-Elemente einlesen und als XML-Attribute ausgeben XML & JSON 7
R sax, stax, jdom, jaxb? List von Objekten speichern und laden XML & JSON 6
J JAXB: Mehrmals abspeichern XML & JSON 3
D XML Einlesen mit JaxB XML & JSON 4
W JAXB Binding customization XML & JSON 4
L JAXB und Interfaces XML & JSON 4
S Problem with JAXB unmarshalling classes that have the same name in @XmlRootElement XML & JSON 2
eykarhorn JAXB namespace attribut aus rootelement entfernen XML & JSON 2
nrg JAXB - nor any of its super class is known to this context XML & JSON 3
S aus XML mit JAXB zu Baumstruktur XML & JSON 3
nrg JAXB generell auf XMLs übertragbar XML & JSON 22
Landei JAXB: Wert von übergeordneten Element XML & JSON 4
B PropertyChangeListener generieren mit JAXB (xjc) XML & JSON 3
G JAXB und verschachtelte Elemente? XML & JSON 6
G JAXB XML-Attribute feststellen XML & JSON 4
S JAXB 2 und JSR 303 XML & JSON 11
R JAXB Unmarshal XML & JSON 2
J JAXB und ArrayList XML & JSON 4
Landei Jpa2 -> jaxb??? XML & JSON 9
M JAXB - HashMap XML & JSON 1
dzim JAXB-Unmarshalling ignoriert/löscht Einträge aus XML - oder lässt sie verschwinden XML & JSON 3
S JAXB 2 und Java Annotationen/Interfaces generieren XML & JSON 3
ruutaiokwu jaxb eclipse plugin... XML & JSON 3
K JAXB: Klassen mit Annotation Lesen/Schreiben XML XML & JSON 3
R JAXB ausgewählte Felder XML & JSON 10
TiME-SPLiNTER JAXB: com.sun.xml.bind.v2.ContextFactory XML & JSON 3
V JAXB und leere Listen XML & JSON 2
L compareto(), equals() in JAXB generierten Dateien XML & JSON 3
D jaxb validierung/verification vor marshalling XML & JSON 3
J JAXB mit GregorianCalendar XML & JSON 4
HombreDelMundo JAXB can't handle interfaces XML & JSON 4
N Individuelles Wrapper-Element um Collection mit JAXB XML & JSON 6
B JAXB Unmarshalling mehrerer Objekte XML & JSON 2
V JAXB schema 2 java XML & JSON 3
B JPA + JAXB Mapping Problem XML & JSON 2
S Navigieren in unbekannten JAXB-Objecten XML & JSON 2
J JAXB NullPointerException im ContextFinder XML & JSON 6
H JAXB und STAX XML & JSON 2
H JAXB Probleme beim Unmarshalling XML & JSON 3
C Serialisierung mit JAXB XML & JSON 6
K JAXB und Maps -> Marshalling-Problem XML & JSON 6
S JAXB und viele verschachtelte Attribute XML & JSON 1
J JAXB - Map XML & JSON 2
O JAXB generierte Klassen sollen Serializable implementieren XML & JSON 1
aze JaxB: Nullelemente in Array nicht anzeigen XML & JSON 3
turmaline JAXB can't handle interfaces XML & JSON 20
sambalmueslie JAXB - Unmarshall ein XML-Document das aus zwei XSD Definitionen besteht XML & JSON 8
S JAXB und abstrakte Klasse(n) XML & JSON 4
P JAXB: Marshalling XML & JSON 7
aze JaxB Elemente in LinkedHashSet werden nicht wiededergegeben XML & JSON 3
M JAXB: Wie folgendes Konstrukt abbilden? XML & JSON 20
A Jaxb und Interfaces XML & JSON 12
B JaxB und XSD :-) XML & JSON 8
G JAXB - Marshaller - kein Rückgabewert XML & JSON 2
N XML will nicht weder JAXB noch XStream XML & JSON 8
F Zugriff auf durch JAXB erzeugte Object-Struktur... XML & JSON 6
C Java-Imports bei Jaxb XML & JSON 8
F Marshaling eines JAXB Objektes worin ein anderes JAXB Objekt eingeschlossen ist XML & JSON 6
K JAXB, Vererbung und Codegeneration XML & JSON 2
M XmlRootElement und JAXB XML & JSON 4
R JAXB: Aus einem Vector oder List XML Datei erstellen XML & JSON 1
G jaxb Vector (oder ähnliches) von Elementen generieren XML & JSON 6
M Jaxb Annotationen, Wert als XML Element XML & JSON 2
J JCheckbox abfragen und serialisieren mit JAXB 2.0 XML & JSON 15
F JAXB erste schritte XML & JSON 6

Ähnliche Java Themen

Neue Themen


Oben