# XML - Bestehende Elemente ändern



## Sherry (21. Jun 2014)

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:


```
/**
 * 
 */
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


----------



## Sherry (22. Jun 2014)

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


```
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();
		}
```


----------

