JAXB und verschachtelte Elemente?

gurkensalat

Mitglied
Hallo,

ich habe folgende XML-Datei/Struktur gegeben:
[XML]<locators>
<locator locatorType="id">
<alias>textbla</alias>
<location>textbla2</location>
</locator>
<locator locatorType="class">
<alias>textblaaaahh</alias>
<location>textblaaaahh2</location>
</locator>
</locators>[/XML]
Das Element locatorkann beliebig oft vorkommen.
Ich komme einfach nicht drauf, wie man eine Java Klasse mit den nötigen JAXB Annotationen zu dieser XML-Datei erstellt. Sämtliche JAXB-Tutorials, die ich über Google gefunden habe, behandeln keine verschachtelten XML-Dateien (schon gar nicht verschachtelte Elemente + Attribute). Kann JAXB sowas gar nicht?
Wie würde für obige XML-Datei eine Java-Klasse aussehen? Wäre für jede Hilfe dankbar, stehe nämlich ziemlich auf dem Schlauch. Danke!

EDIT: Mein bisheriger (falscher, nicht funktionierender) Ansatz:
Java:
@XmlRootElement(name="locators") 
@XmlAccessorType(XmlAccessType.NONE)
public class Locators {
	@XmlElement(name="locators", required=true)
	private ArrayList<Locator> locators;
	
	public Locators(){
		locators = new ArrayList<Locator>();
	}
	
	private class Locator{
		@XmlElement(name="alias", required=true)
		String alias;
		@XmlAttribute(name="locatorType", required=true)
		String locatorType;
		@XmlElement(name="location", required=true)
		String location; 
    }
}
 
Zuletzt bearbeitet:

eRaaaa

Top Contributor
Klar, es muss in Zeile 4 ja auch
Java:
@XmlElement(name="locator", required=true)

heißen :) (name="locator" anstatt locators!)

Aber die Exception die du vermutlich erhältst kannst du umgehen indem du die Locator-Klasse static machst
Also alles in allem so
Java:
@XmlRootElement(name = "locators")
@XmlAccessorType(XmlAccessType.NONE)
class Locators {
	@XmlElement(name = "locator", required = true)  //hier geanedert
	private ArrayList<Locator> locators;

	public Locators() {
		locators = new ArrayList<Locator>();
	}

	private static class Locator { //hier geanedert
		@XmlElement(name = "alias", required = true)
		String alias;
		@XmlAttribute(name = "locatorType", required = true)
		String locatorType;
		@XmlElement(name = "location", required = true)
		String location;
	}
}
 
Zuletzt bearbeitet:

gurkensalat

Mitglied
Mh, irgendwie werde ich noch nicht ganz schlau draus.

Java:
@XmlElement(name = "locator", required = true)  //hier geanedert
    private ArrayList<Locator> locators;
Also einmal locator und einmal ne Liste locators. ???:L Ahhh, total konfus ^^

Mh, ich werde es mal anders versuchen. Ich habe eine Klasse XY, diese hat eine HashMap. Diese HashMap soll alle locator Elemente aus dem XML-File speichern. Der Key ist dabei das Alias-Element und der Value ist dabei eine Klasse Locator. Die Klasse Locator hat die zwei Attribute locatorType und location. Ich versuche es mal als Code darzustellen:
Java:
public class XY{
	private HashMap<String, Locator> map = new HashMap<String, Locator>();
}
Java:
public class Locator{
	private String locatorType;
	private String location;
}

Jedes locator-Element aus der XML-Datei soll also einen Eintrag in der HashMap erzeugen. Denke ich da in die falsche Richtung? Irgendwelche Ansätze?
 

eRaaaa

Top Contributor
Mh, irgendwie werde ich noch nicht ganz schlau draus.

Java:
@XmlElement(name = "locator", required = true)  //hier geanedert
    private ArrayList<Locator> locators;
Also einmal locator und einmal ne Liste locators. ???:L Ahhh, total konfus ^^

Naja du musst eben unterscheiden zwischen XML und Java :) Es ginge auch
Java:
	@XmlElement
	private ArrayList<Locator> locator;

Was aber eine ziemlich schlechte Namenswahl wäre! Wenn du deine Liste eben locators nennen willst, musst du eben sagen, zu welchem XML Element "gemapped" werden soll -> und es soll ja <locator> .. Objekte dort gespeichert werden, also musst du das eben dann sagen/angeben mit name = ... in der Annotation...


Mh, ich werde es mal anders versuchen.[...]
Was gefällt dir nicht am anderen Ansatz? Der funktioniert doch und das war schließlich das was du zu Beginn wolltest ?!
 

gurkensalat

Mitglied
Was gefällt dir nicht am anderen Ansatz? Der funktioniert doch und das war schließlich das was du zu Beginn wolltest ?!
Der Ansatz ist okay, und danke auch für deine schnelle Hilfe! Das Problem ist aber, dass ich in Java eben das anders vorgegeben habe, nämlich mit der HashMap und der Locator Klasse. Darum kann ich das mit der inneren Klasse nicht machen. Mh.. ich komm da total durcheinander mit der Namensgebung und werd irgendwie immer noch nicht so richtig schlau draus. Tut mir Leid, wenn ich mich blöd anstelle :D

EDIT:
Also wie gesagt, ich habe folgendes gegeben:
[XML]<locators>
<locator locatorType="id">
<alias>textbla</alias>
<location>textbla2</location>
</locator>
<locator locatorType="class">
<alias>textblaaaahh</alias>
<location>textblaaaahh2</location>
</locator>
</locators>[/XML]

Java:
public class XY{
    private HashMap<String, Locator> map = new HashMap<String, Locator>();
    public void readFromXmlFile(){magic magic}
}

public class Locator{
    private String locatorType;
    private String location;
}
Die Klasse XY liest quasi die XML Datei ein und erstellt pro locator-Element eine Locator-Klasse und speichert die dann in ihre HashMap, mit dem alias-Element als Key.
 
Zuletzt bearbeitet:

gurkensalat

Mitglied
Okay, ich weiß nicht, was gestern los war, vllt die Hitze oder so ^^
Habs eben grade nochmal ausprobiert mit folgendem Aufbau (das ist dein Vorschlag):
Java:
@XmlRootElement(name = "locators")
class Locators {
	public enum LocatorType{
		ID,
		CLASS,
		XPATH,
		LINK,
		CSS,
		NAME,
		TAG;
	}
	
    @XmlElement(name = "locator", required = true)
    public ArrayList<Locator> locator;
 
    public Locators() {
        locator = new ArrayList<Locator>();
    }
 
    public static class Locator {
        @XmlElement(name = "alias", required = true)
        String alias;
        @XmlAttribute(name = "locatorType", required = true)
        LocatorType locatorType;
        @XmlElement(name = "location", required = true)
        String location;
    }
}
Das funktioniert wunderbar, so lange der locatorType vom Typ String ist. Jetzt habe ich mal versucht einen Enum mit einzubauen und eben diesen Typen zu vergeben, aber da bleibt dann das Attribut locatorType null beim Einlesen der xml-Datei. Gibt es generell eine Lösung für sowas? Oder kann man nur Strings einlesen, bzw primitive Datentypen?

EDIT: Ha! Man sollte vllt erstmal selber ausprobieren :D Für alle die es interessiert: Im XML-File müssen ID und CLASS groß geschrieben werden, wie eben in der Java Klasse bei dem Enum auch. Danke für die Hilfe!
 
Zuletzt bearbeitet:

mvitz

Top Contributor
Ansonsten hilft es meiner Meinung nach auf oft, wenn man sich das XML Schema zusammenbaut und dann mal guckt, was der XJC daraus macht, für dein Beispiel sieht das dann folgendermaßen aus:
[XML]<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:tns="http://www.mvitz.de/test/jf/jaxb"
targetNamespace="http://www.mvitz.de/examples/jaxb/enum/">

<xs:element name="locators" type="tns:locators" />

<xs:complexType name="locators">
<xs:sequence>
<xs:element name="locator" type="tns:locator" maxOccurs="unbounded" />
</xs:sequence>
</xs:complexType>

<xs:complexType name="locator">
<xs:sequence>
<xs:element name="alias" type="xs:string" />
<xs:element name="location" type="xs:string" />
</xs:sequence>
<xs:attribute name="locatorType" type="tns:locatorType" use="required" />
</xs:complexType>

<xs:simpleType name="locatorType">
<xs:restriction base="xs:string">
<xs:enumeration value="ID" />
<xs:enumeration value="CLASS" />
<xs:enumeration value="XPATH" />
<xs:enumeration value="LINK" />
<xs:enumeration value="CSS" />
<xs:enumeration value="NAME" />
<xs:enumeration value="TAG" />
</xs:restriction>
</xs:simpleType>

</xs:schema>[/XML]
Java:
package de.mvitz.examples.jaxb.generic;

import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;


/**
 * <p>Java class for locators complex type.
 * 
 * <p>The following schema fragment specifies the expected content contained within this class.
 * 
 * <pre>
 * &lt;complexType name="locators">
 *   &lt;complexContent>
 *     &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       &lt;sequence>
 *         &lt;element name="locator" type="{http://www.mvitz.de/examples/jaxb/enum/}locator" maxOccurs="unbounded"/>
 *       &lt;/sequence>
 *     &lt;/restriction>
 *   &lt;/complexContent>
 * &lt;/complexType>
 * </pre>
 * 
 * 
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "locators", propOrder = {
    "locator"
})
public class Locators {

    @XmlElement(required = true)
    protected List<Locator> locator;

    /**
     * Gets the value of the locator property.
     * 
     * <p>
     * This accessor method returns a reference to the live list,
     * not a snapshot. Therefore any modification you make to the
     * returned list will be present inside the JAXB object.
     * This is why there is not a <CODE>set</CODE> method for the locator property.
     * 
     * <p>
     * For example, to add a new item, do as follows:
     * <pre>
     *    getLocator().add(newItem);
     * </pre>
     * 
     * 
     * <p>
     * Objects of the following type(s) are allowed in the list
     * {@link Locator }
     * 
     * 
     */
    public List<Locator> getLocator() {
        if (locator == null) {
            locator = new ArrayList<Locator>();
        }
        return this.locator;
    }

}
Java:
package de.mvitz.examples.jaxb.generic;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;


/**
 * <p>Java class for locator complex type.
 * 
 * <p>The following schema fragment specifies the expected content contained within this class.
 * 
 * <pre>
 * &lt;complexType name="locator">
 *   &lt;complexContent>
 *     &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       &lt;sequence>
 *         &lt;element name="alias" type="{http://www.w3.org/2001/XMLSchema}string"/>
 *         &lt;element name="location" type="{http://www.w3.org/2001/XMLSchema}string"/>
 *       &lt;/sequence>
 *       &lt;attribute name="locatorType" use="required" type="{http://www.mvitz.de/examples/jaxb/enum/}locatorType" />
 *     &lt;/restriction>
 *   &lt;/complexContent>
 * &lt;/complexType>
 * </pre>
 * 
 * 
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "locator", propOrder = {
    "alias",
    "location"
})
public class Locator {

    @XmlElement(required = true)
    protected String alias;
    @XmlElement(required = true)
    protected String location;
    @XmlAttribute(required = true)
    protected LocatorType locatorType;

    public String getAlias() {
        return alias;
    }

    public void setAlias(String value) {
        this.alias = value;
    }

    public String getLocation() {
        return location;
    }

    public void setLocation(String value) {
        this.location = value;
    }

    public LocatorType getLocatorType() {
        return locatorType;
    }

    public void setLocatorType(LocatorType value) {
        this.locatorType = value;
    }

}
Java:
package de.mvitz.examples.jaxb.generic;

import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlType;


/**
 * <p>Java class for locatorType.
 * 
 * <p>The following schema fragment specifies the expected content contained within this class.
 * <p>
 * <pre>
 * &lt;simpleType name="locatorType">
 *   &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string">
 *     &lt;enumeration value="ID"/>
 *     &lt;enumeration value="CLASS"/>
 *     &lt;enumeration value="XPATH"/>
 *     &lt;enumeration value="LINK"/>
 *     &lt;enumeration value="CSS"/>
 *     &lt;enumeration value="NAME"/>
 *     &lt;enumeration value="TAG"/>
 *   &lt;/restriction>
 * &lt;/simpleType>
 * </pre>
 * 
 */
@XmlType(name = "locatorType")
@XmlEnum
public enum LocatorType {

    ID,
    CLASS,
    XPATH,
    LINK,
    CSS,
    NAME,
    TAG;

    public String value() {
        return name();
    }

    public static LocatorType fromValue(String v) {
        return valueOf(v);
    }

}
 
Ähnliche Java Themen
  Titel Forum Antworten Datum
S JAXB und viele verschachtelte Attribute XML & JSON 1
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 XML-Attribute feststellen XML & JSON 4
S JAXB 2 und JSR 303 XML & JSON 11
M [JAXB] @XmlAnyElement namespace XML & JSON 4
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
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