XML - Bestehende Elemente ändern

Sherry

Aktives Mitglied
Hallo,

ich habe eine XML-Datei wie hier
[XML]<?xml version="1.0" encoding="UTF-8"?>
<costcalculator>
<city name="München">
<distance>221.357</distance>
<duration>2.3294444444444444</duration>
<monthlyticket>547.00</monthlyticket>
<roundtripdticket>114.0</roundtripdticket>
<hotelcosts>0.00</hotelcosts>
<flightcost>0.00</flightcost>
</city>
<city name="Frankfurt">
<distance>204.365</distance>
<duration>2.0494444444444446</duration>
<monthlyticket>467.00</monthlyticket>
<roundtripdticket>126.00</roundtripdticket>
<hotelcosts>0.00</hotelcosts>
<flightcost>0.00</flightcost>
</city>
<city name="Köln">
<distance>367.153</distance>
<duration>3.4047222222222224</duration>
<monthlyticket>292.40</monthlyticket>
<roundtripdticket>185.00</roundtripdticket>
<hotelcosts>49.00</hotelcosts>
<flightcost>0.00</flightcost>
</city>
</costcalculator>
[/XML]

Das Neuanlegen von XML-Knoten und deren Elementen mit Inhalten klappt mit der Klasse XMLCreator:

Java:
/**
 * 
 */
package com.errata.calculator;

import static com.errata.calculator.Constants.ATTRIBUTE_NAME;
import static com.errata.calculator.Constants.ELEMENT_CITY;
import static com.errata.calculator.Constants.ELEMENT_DISTANCE;
import static com.errata.calculator.Constants.ELEMENT_DURATION;
import static com.errata.calculator.Constants.ELEMENT_FLIGHTCOST;
import static com.errata.calculator.Constants.ELEMENT_HOTEL;
import static com.errata.calculator.Constants.ELEMENT_TICKET;
import static com.errata.calculator.Constants.ELEMENT_DTICKET;
import static com.errata.calculator.Constants.ORIGIN_CITY;
import static com.errata.calculator.Constants.PATH;

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

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPathExpressionException;

import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.Namespace;
import org.jdom2.input.SAXBuilder;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;
import org.jdom2.xpath.XPath;
import org.xml.sax.SAXException;


public class XMLCreator {
	private String path = System.getProperties().getProperty("user.home")+File.separator+PATH+File.separator+ORIGIN_CITY+"City.xml";
	/*
	 * Abfrage, ob xml-Datei bereits existiert!!!
	 */
	private File xmlFile = new File(path);
	private Namespace ns = Namespace.getNamespace("http://www.errata.com/Preiskalkulator");
	String origin = ORIGIN_CITY;
	String cityName;
	String ticket = "0.0";
	String hotel = "0.0";
	String flightcost = "0.0";

	public XMLCreator() {
		super();
	}
	
	public void writeXML(String cityName, String ticket, String dticket, String hotel, String flightcost) throws XPathExpressionException, SAXException, ParserConfigurationException, JDOMException {
		Parser distance = new Parser();
		Parser duration = new Parser();
		try {
			SAXBuilder builder = new SAXBuilder();
			Document document = builder.build(xmlFile);

			Element xmlRoot = document.getRootElement();
			Element city = new Element(ELEMENT_CITY);
			city.setAttribute(ATTRIBUTE_NAME, cityName);
			city.addContent(new Element(ELEMENT_DISTANCE).setText(String.valueOf(distance.parsedistance(origin, cityName))));
			city.addContent(new Element(ELEMENT_DURATION).setText(String.valueOf(duration.parseduration(origin, cityName))));
			city.addContent(new Element(ELEMENT_TICKET).setText(ticket));
			city.addContent(new Element(ELEMENT_DTICKET).setText(dticket));
			city.addContent(new Element(ELEMENT_HOTEL).setText(hotel));
			city.addContent(new Element(ELEMENT_FLIGHTCOST).setText(flightcost));
			xmlRoot.addContent(city);

			XMLOutputter xmlOutput = new XMLOutputter();
			xmlOutput.setFormat(Format.getPrettyFormat());
			xmlOutput.output(document, new FileWriter(path));

		} catch (IOException e) {
			e.printStackTrace();
		} 
		
	}
	
	public List<String> readXML(String cityName) {
		List<String> results  = new ArrayList<String>();
		Document doc;
		try {
			SAXBuilder builder = new SAXBuilder();
			doc = (Document) builder.build(xmlFile);

			List<Element> nodes;
			nodes = (List<Element>) XPath.selectNodes(doc, "/costcalculator/city");
				
			for (Element element : nodes) {
				if (cityName.equals(element.getAttributeValue("name"))) {
					results.add(element.getAttributeValue("name"));
					results.add(element.getChildText("distance"));
					results.add(element.getChildText("duration"));
					results.add(element.getChildText("monthlyticket"));
					results.add(element.getChildText("roundtripdticket"));
					results.add(element.getChildText("hotelcosts"));
					results.add(element.getChildText("flightcost"));	
				} 
			}
		} catch (JDOMException | IOException e) {
			e.printStackTrace();
		}
		return results;				
	}

	public void changeXML(String cityName, String monthlyTicket, String roundTripTicket, String hotel, String flightTicket) {
		List<String> elements  = new ArrayList<String>();
		Document doc;
		try {
			SAXBuilder builder = new SAXBuilder();
			doc = (Document) builder.build(xmlFile);

			List<Element> nodes;
			nodes = (List<Element>) XPath.selectNodes(doc, "/costcalculator/city");
				
			for (Element element : nodes) {
				if (cityName.equals(element.getAttributeValue("name"))) {
					elements.add(element.removeChild("monthlyticket"));
				} 
			}
			
			XMLOutputter xmlOutput = new XMLOutputter();
			xmlOutput.setFormat(Format.getPrettyFormat());
			xmlOutput.output(doc, new FileWriter(path));
			
		} catch (JDOMException | IOException e) {
			e.printStackTrace();
		}
	}
	
	public List<String> CityList() {
		Document doc;
		List<String> CityList = new ArrayList<String>();
		try {
			SAXBuilder builder = new SAXBuilder();
			doc = (Document) builder.build(xmlFile);

			List<Element> nodes;
			nodes = (List<Element>) XPath.selectNodes(doc, "/costcalculator/city");
			for (Element element : nodes) {
				CityList.add(element.getAttribute("name").getValue());
			}
			
		} catch (JDOMException | IOException e) {
			e.printStackTrace();
		}
		return CityList;
	}
	
}
Ich möchte aber auch die Werte der einzelnen Elemente ändern können, indem ich zum Beispiel nach der Stadt München suchen lassen, um dann dort die einzelnen Werte ändern zu können. Das soll die Methode "changeXML" erledigen. Dazu baue ich mir wieder ein Dokument mit der Abbildung des XML-Baums und weise dieses einer Liste zu, die nach dem Attribut der Stadt München durchsuchen lassen.
Im Insel-Buch bin ich auf zwei Methoden der Elemente-Klasse gestossen, setText() und aadContent(). Wobei von setText() abgeraten wird und man zuerst mit removeChild() das Element löschen soll. Um dann es mit addContent() und neuen Inhalt wieder anlegen soll.
Ich finde jetzt keinen Ansatz das in der Liste durchzuführen. Ich finde auch keine Beispiele, die mir die Vorgehensweise zeigen könnten.
Könnt Ihr mir vielleicht weiterhelfen?

Vielen Dank und Grüße
Sherry
 
Zuletzt bearbeitet:

Sherry

Aktives Mitglied
Dann löse ich das der Vollständigkeithalber eben selber:

Java:
try {
			SAXBuilder builder = new SAXBuilder();
			doc = (Document) builder.build(xmlFile);

			Element costCalculator = doc.getRootElement();
			
			Iterator<?> cityList = costCalculator.getChildren("city").iterator();
			while (cityList.hasNext()) {
				Element city = (Element) cityList.next();
				if (cityName.equals(city.getAttribute("name").getValue())) {
					Element monthlyTicket = new Element("monthlyticket");
					monthlyTicket.addContent("205.00");
					city.removeChild("monthlyticket");
					city.addContent(monthlyTicket);
					Element roundTripTicket = new Element("roundtripticket");
					roundTripTicket.addContent("82.00");
					city.removeChild("roundtripticket");
					city.addContent(roundTripTicket);
					Element hotelCost = new Element("hotelcosts");
					hotelCost.addContent("55.00");
					city.removeChild("hotelcosts");
					city.addContent(hotelCost);
					Element flightTicket = new Element("flightcost");
					flightTicket.addContent("278.00");
					city.removeChild("flightcost");
					city.addContent(flightTicket);
				}
				
			}
			
			XMLOutputter xmlOutput = new XMLOutputter();
			xmlOutput.setFormat(Format.getPrettyFormat());
			xmlOutput.output(doc, new FileWriter(path));
			
		} catch (JDOMException | IOException e) {
			e.printStackTrace();
		}
 


Schreibe deine Antwort... und nutze den </> Button, wenn du Code posten möchtest...
Ähnliche Java Themen
  Titel Forum Antworten Datum
L XML einlesen gleichnamige Elemente XML & JSON 5
J Parent- und Child-Elemente mit gleiche Namen, geht das ? XML & JSON 1
C JAXB: XML-Elemente einlesen und als XML-Attribute ausgeben XML & JSON 7
R Verschachtelung gleichnamiger Elemente XML & JSON 7
D optionale Elemente mit defaultwerten werden in xml miterzeugt XML & JSON 2
A Elemente aus mehreren XML-Dateien zu einem zusammenfügen XML & JSON 5
G JAXB und verschachtelte Elemente? XML & JSON 6
J Anzahl der Elemente in einem XML-Dokument auslesen XML & JSON 7
F Hilfe beim bearbeiten von XML elemente XML & JSON 3
G Wieviele Elemente von TagName, ich brings nicht hin XML & JSON 5
G Leere Elemente verhindern XML & JSON 7
aze JaxB Elemente in LinkedHashSet werden nicht wiededergegeben XML & JSON 3
E XML Datei einlesen und Elemente in der Console ausgeben XML & JSON 6
D Tabs/Einrückungen der XML-Elemente gehen beim Schreiben verloren XML & JSON 5
Z XML auslesen, Elemente daraus entfernen und als neue XML zurückgeben XML & JSON 2
S JTree - Nur Elemente mit Attributen einfügen XML & JSON 2
T Elemente zählen mit JDOM in XML XML & JSON 7
G XML Parser Fehler, zwei gleiche kind-Elemente XML & JSON 7
F Elemente sortieren lassen XML & JSON 2
I Editor, der nur Elemente einfuegt, die nach xsd zulaessig XML & JSON 2
G xml einlesen und bestimmte Elemente an eine gui_Klasse überg XML & JSON 25
H Elemente eines Node auslesen XML & JSON 2
M XML Elemente mit JDOM durch Text ersetzen XML & JSON 2
P JDom nimmt keine Elemente an. XML & JSON 3
M Elemente mit Prefix via JDOM erstellen XML & JSON 6
J Jdom Elemente lesen XML & JSON 5
P zugriff auf gewuenschte elemente klapp nicht. XML & JSON 3
T Einfach nur die Elemente einer XML Datei auslesen :( XML & JSON 10
T Elemente aus XML-File löschen (JDom) XML & JSON 9
G Xml Elemente in eine Liste abspeichern! XML & JSON 2
G Elemente in XML XML & JSON 4
G brauche Tips, wie ich am besten auf Elemente zugreife XML & JSON 5
D Xml-Datei in JTree anzeigen und Elemente ausblenden XML & JSON 2
S JDOM Elemente suchen XML & JSON 2
H JSON-Code ändern XML & JSON 0
B Wie kann man das ecncoding in einem vorhandenen Document-Objekt ändern? XML & JSON 2
A JDOM: Wert schreiben bzw. ändern XML & JSON 6
L Zeichen in XML ändern XML & JSON 4
I JDom Text ändern XML & JSON 4
W JDOM element ändern funzt nich :( [problem gelöst] XML & JSON 3
J DOM: Attribut und Inhalt eines Elements nachträglich ändern? XML & JSON 3
B xml datei über gui ändern XML & JSON 4
G JDom encoding ändern XML & JSON 2
M XML Einträge ändern XML & JSON 3

Ähnliche Java Themen

Neue Themen


Oben