Leeres Array beim Auslesen von XML-Datei

Adhiambo

Mitglied
Hallo guten Morgen,

ich möchte aus dieser XML-Datei den Discount-Wert des entsprechenden condtions-Tags auslesen.
Conditions.xml
Code:
<?xml version="1.0" encoding="UTF-8"?>
<conditions>
  <condition name="Ohne Skonto">
    <discount>0.00</discount>
  </condition>
  <condition name="5 Tage">
    <discount>2</discount>
  </condition>
</conditions>

Dazu habe ich folgende Java-Klasse "ReadConditions.java"
Java:
package tld.software.calculator;

public class ReadConditions {
    private XMLConditonsCreator element;
    public static void main(String[] args) {
        XMLConditonsCreator element = new XMLConditonsCreator();
        System.out.println(element.readXml("Ohne Skonto"));
    }
}
und die beiden Klassen, die importiert werden:
Constants.java:
Java:
package tld.software.calculator;

public class Constants {
    public final static String ATTRIBUTE_NAME = "name";
    public final static String ELEMENT_CONDITIONS = "conditions";
    public final static String ELEMENT_CONDITION = "condition";;
    public final static String ELEMENT_DISCOUNT = "discount";
}
XMLConditonsCreator.java:
Java:
package tld.software.calculator;

import static tld.software.calculator.Constants.ATTRIBUTE_NAME;
import static tld.software.calculator.Constants.ELEMENT_CONDITIONS;
import static tld.software.calculator.Constants.ELEMENT_CONDITION;
import static tld.software.calculator.Constants.ELEMENT_DISCOUNT;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;

import org.jdom2.*;
import org.jdom2.Element;
import org.jdom2.input.SAXBuilder;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;
import org.jdom2.xpath.XPathFactory;
import org.jdom2.xpath.XPathExpression;
import org.xml.sax.SAXException;

import javax.xml.xpath.XPathExpressionException;

public class XMLConditonsCreator {
    private static String conditionFile = System.getProperties().getProperty("user.home")
            +File.separator+PlatformDependence.offerValue("directory")+File.separator + "Conditions.xml";
    private static File xmlFile = new File(conditionFile);
    private Namespace ns = Namespace.getNamespace("http://local.software.tld/calculator");
    private SAXBuilder builder = new SAXBuilder();
    private Document jdomDoc;

    public XMLConditonsCreator() {
        super();
    }

    public List<String> readXml(String conditionName) {
        List<String> results  = new ArrayList<String>();
        List<Element> elements = getConditionsElements(conditionName);
        if (elements != null) {
            results.add(conditionName);
            for (Element element : elements) {
                results.add(element.getValue());
            }
        }
        return results;
    }

    private static List<Element> getRootElements() {
        SAXBuilder builder = null;
        Document jdomDoc = null;
        try {
            builder = new SAXBuilder();
            jdomDoc = builder.build(xmlFile);
        } catch (JDOMException | IOException ex) {
            System.err.println(ex);
        }
        if (builder != null && jdomDoc != null) {
            return jdomDoc.getRootElement().getChildren();
        } else {
            return null;
        }
    }

    private static List<Element> getConditionsElements(String conditionName) {
        List<Element> serviceList = getRootElements();
        if (serviceList != null) {
            for (Element element : serviceList) {
                try {
                    if (element.getAttribute("name").equals(conditionName)) {
                        return element.getChildren();
                    }
                } catch ( NullPointerException ex ) {
                    ex.printStackTrace();
                    System.out.println("getConditionsElements wirft diese Exception");
                }
            }
        }
        return null;
    }

    public List<String> ConditionList() {
        List<String> ConditionList = new ArrayList<>();
        try {
            if (new File(System.getProperties().getProperty("user.home")+
                    File.separator+PlatformDependence.offerValue("directory")+
                    File.separator+PlatformDependence.offerValue("setting")).exists()) {
                jdomDoc = builder.build(xmlFile);
            }
            XPathFactory xFactory = XPathFactory.instance();
            XPathExpression xpath = xFactory.compile("conditions/condition/@name");
            for (Object opject : xpath.evaluate(jdomDoc)) {
                ConditionList.add(((Attribute)opject).getValue());
            }
        } catch (JDOMException | IOException ex) {
            ex.printStackTrace();
        }
        return ConditionList;
    }
}

Mein Problem ist, dass diese Konstruktion ein leeres Array zurückliefert, obwohl ein Array mit einem Wert zurückkommen müsste.
Wenn ich die ReadConditions.java mit dem Debugger starte und den Breakpoint bei System.out.println setze, sehe ich dass alles fehlerfrei durchläuft. Nur der Rückgabewert in readXml(String conditionName) results liefert "size=0" und in der For-Schleife ist "elements: null". So wird der Hauptklasse ein leeres Array als Ergebnis übergeben.

Ich sehe im Moment nicht, wo mein Ansatzfehler ist. Vielleicht könnt ihr mich bei der Suche unterstützen?

Vielen Dank
Adhiambo
 

Joose

Top Contributor
Wenn ich die ReadConditions.java mit dem Debugger starte ......

Ich sehe im Moment nicht, wo mein Ansatzfehler ist. Vielleicht könnt ihr mich bei der Suche unterstützen?
Hast du auch schon mal weiter in den Code debuggt? Die Methode getConditionsElements dürfte ja anscheinend nicht die gesuchten Felder liefern.
Schon mal kontrolliert was dort passiert?
 

Flown

Administrator
Mitarbeiter
Musst du das alles händisch parsen? Geht doch viel einfacher mit JAXB und ist weit nicht so fehleranfällig wie dein Murks:
Java:
import java.io.StringReader;
import java.util.List;

import javax.xml.bind.JAXB;
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.XmlRootElement;
import javax.xml.bind.annotation.XmlSeeAlso;

public class Test {
  public static void main(String... args) {
    String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +
        "<conditions>\r\n" +
        "  <condition name=\"Ohne Skonto\">\r\n" +
        "    <discount>0.00</discount>\r\n" +
        "  </condition>\r\n" +
        "  <condition name=\"5 Tage\">\r\n" +
        "    <discount>2</discount>\r\n" +
        "  </condition>\r\n" +
        "</conditions>";
    System.out.println(JAXB.unmarshal(new StringReader(xml), Conditions.class));
  }
}

@XmlRootElement(name = "conditions")
@XmlAccessorType(XmlAccessType.NONE)
@XmlSeeAlso({ Condition.class })
class Conditions {
  @XmlElement(name = "condition")
  List<Condition> conditions;

  public List<Condition> getConditions() {
    return conditions;
  }

  public void setConditions(List<Condition> conditions) {
    this.conditions = conditions;
  }

  @Override
  public String toString() {
    return "Conditions [" + conditions + "]";
  }

}

@XmlAccessorType(XmlAccessType.NONE)
class Condition {
  @XmlAttribute(name = "name", required = true)
  private String name;
  @XmlElement(name = "discount")
  private double discount;

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public double getDiscount() {
    return discount;
  }

  public void setDiscount(double discount) {
    this.discount = discount;
  }

  @Override
  public String toString() {
    return "Condition [name=" + name + ", discount=" + discount + "]";
  }

}
 
Ähnliche Java Themen
  Titel Forum Antworten Datum
M xPath liefert leeres Nodeset XML & JSON 2
Z json inkl. Array/Verschachtelung erstellen XML & JSON 2
J Object in JSON Datei einlesen und als neues Object erzeugen (in ein Object Array) XML & JSON 29
L Button-Array in XML XML & JSON 1
Y XML in ein Byte Array transformieren XML & JSON 8
aze JaxB: Nullelemente in Array nicht anzeigen XML & JSON 3
L XML Daten auslesen und in Tabelle (Array) speichern XML & JSON 1
S byte array in xslt umwandeln XML & JSON 7
J XML-Datei ein Array einlesen XML & JSON 10
I Mit JDOM Daten aus XML in ein Array abfüllen XML & JSON 4
W Ungleiches Escaping beim Marshalling XML & JSON 8
S Hilfe beim RDF-Graphen XML & JSON 0
R Beim Serialisieren fehlt die letzte Zeile XML & JSON 5
N Probleme bei der Formatierung beim Einfügen und löschen über DOM XML & JSON 7
L Jackson JSON: Probleme beim einlesen XML & JSON 1
A XML-Fehler beim Prefix von xmlns XML & JSON 2
K Beim Parsen einer XML-Datei Connection timed out XML & JSON 4
G Langsam beim SAX-Parsen - woran liegts? XML & JSON 2
A Fehler beim Erzeugen eines XML-Schema XML & JSON 4
B Validierung nur beim einlesen oder auch beim schreiben? XML & JSON 4
D JAXBException beim Marshaller XML & JSON 4
M Read / write Problem beim ByteStrom XML & JSON 2
whitenexx Problem beim parsen von Facebook XML XML & JSON 3
J Dateinamen beim Start auslesen XML & JSON 8
F Hilfe beim bearbeiten von XML elemente XML & JSON 3
N XStream ConversionException beim Deserialisieren in (Hibernate)Objekt XML & JSON 6
hdi Probleme beim Erstellen einer XML XML & JSON 7
F Probleme beim html parsen mit tagsoup XML & JSON 4
M Probleme beim Parsen eines gefilterten XML-Dokuments XML & JSON 6
G Problem beim schreiben von XML in eine File XML & JSON 2
L Reihenfolge beim xml Datei parsen einhalten? XML & JSON 8
H JAXB Probleme beim Unmarshalling XML & JSON 3
sylo Beim Erzeugen einer XML Datei auch die XML Struktur erzeugen? XML & JSON 11
B Problem beim löschen von ChildNodes aus einem XML-DOM XML & JSON 3
E JDOM - Problem beim Zusammenfügen zweier Dateien XML & JSON 2
N Hilfe beim Einstieg in EMF XML & JSON 6
D Das Programm hängt etwa 5 Sekunden beim Aufruf der parse-Methode XML & JSON 6
D Tabs/Einrückungen der XML-Elemente gehen beim Schreiben verloren XML & JSON 5
T Problem beim Parsen von Attribut xmlns="urn:com:test&qu XML & JSON 6
G XML Tag beim Einlesen manipulieren XML & JSON 2
J Problem beim XML-Lesen XML & JSON 2
S Probleme beim erstellen einer Jar XML & JSON 12
N jdom problem beim lesen von child elementen XML & JSON 5
P NullPointerException beim Auslesen XML & JSON 8
M Performance beim Binding XML & JSON 2
C SAX Probleme beim lesen XML & JSON 4
D Probleme beim SAX parsing XML & JSON 4
E XOM setzen von XML-Schema declaration beim erzeugen XML-File XML & JSON 2
byte Probleme beim Parsen von XHTML-Datei XML & JSON 4
J Fehler beim laden einer .xml XML & JSON 3
G DOCTYPE Problem beim Transformer/TransformerFactory etc. XML & JSON 13
P OutOfMemoryError beim Einlesen einer XML-Datei XML & JSON 7
P Problem beim erstellen eines neuen Elements (JDOM) XML & JSON 5
S JDOM-Kein indent beim XMLOutputter XML & JSON 4
C Zeile herausfinden in der ein Fehler beim Einlesen entsteht XML & JSON 3
V Datenverlust nach sortieren (nur beim serialisieren) XML & JSON 4
S Problem beim Erstellen eines pdfs XML & JSON 3
R Problem beim Auslesen von Attributen XML & JSON 4
R JAVA und DOM, probleme beim einfügen von elementen ?????? XML & JSON 6

Ähnliche Java Themen

Neue Themen


Oben