EasyXml class

Simple read and write access to XML documents through XPath expressions. Automatically creates missing XML elements when writing with XPath.

Das Problem

Für den Umgang mit XML-Dokumenten bieten viele Anwendungs-Frameworks wie auch .NET eigene Klassen und Funktionen an. Meistens orientiert sich die Struktur dieser Klassen an DOM und XPath. Damit können die einzelnen Aspekte eines XML-Dokuments sehr detailliert betrachtet und eingestellt werden. Mit XPath-Abfragen können auch relativ einfach bestimmte Elemente aus einem umfangreichen Dokument adressiert werden. Doch beim Erstellen eines neuen XML-Dokuments oder beim Hinzufügen neuer Elemente ist weitgehend „Handarbeit“ angesagt: Jedes Element muss einzeln erstellt werden, eine Referenz darauf muss gehalten werden und weitere Unterelemente müssen dem hinzugefügt werden. Das erfordert mehrere Codezeilen pro Element(ebene), lenkt von der eigentlichen Aufgabe und Dokumentstruktur ab und führt zu unübersichtlichem Code.

Die Lösung

Die EasyXml-Klasse stellt konsistente Methoden bereit, mit denen XPath-Ausdrücke zum Lesen vorhandener aber auch zum Erstellen neuer Elemente verwendet werden können. So können Textinhalte von Elementen oder einzelne Attribute ausgewählt werden. Der gelesene Wert kann direkt als Zeichenkette, Zahl, boolscher Wert, Zeitangabe oder Farbwert interpretiert werden. Weitere Datentypen können im Quelltext hinzugefügt werden. Zum Erstellen von Elementen wird ein vereinfachter XPath-Ausdruck verwendet, der feste Pfadangaben zu einem Element und optional einem Attribut enthält. Alle Elemente dieser Hierarchie werden bei Bedarf automatisch erstellt. Um Auflistungen von Elementen zu erzeugen, kann optional auch eine neue Instanz des untersten Elements angelegt werden. Die unterstützten Datentypen werden automatisch in die passende String-Darstellung konvertiert. Und um auch in komplexeren Dokumenten den Wert an die richtige Stelle zu schreiben, kann eine XmlNode-Instanz als Basis für den XPath-Ausdruck angegeben werden.

Compatibility: .NET Version 2.0 or newer

Beispiel

Der folgende Beispielcode zeigt, wie die EasyXml-Klasse verwendet werden kann:

// Create a new XML document
EasyXml ex = new EasyXml();

// Create some general elements with attributes
ex.Write("/plot/time/@start", startTime);
ex.Write("/plot/time/@end", endTime);
if (duration != null)
{
    ex.Write("/plot/time/@duration", duration);
}
ex.Write("/plot/size/@width", imageSize.Width);
ex.Write("/plot/size/@height", imageSize.Height);

foreach (SourceConfiguration config in selectedConfigurations)
{
    // Find a suitable Y axis for this source
    int yAxisNum = 0;
    // You can access the managed XML document with the usual .NET classes at any time.
    XmlNodeList yAxes = ex.XmlDocument.SelectNodes("/plot/yaxis");
    for (int i = 0; i < yAxes.Count; i++)
    {
        XmlNode yAxisNode = yAxes[i];
        // Read from the found XML node as starting point.
        // Don't use rooted XPath expressions then (no "/" at the beginning).
        string unit = ex.ReadString(yAxisNode, "unit", null);

        if (someMatchingCriteria)
        {
            yAxisNum = i + 1;
            break;
        }
    }
    if (yAxisNum == 0)
    {
        // No Y axis found, create a new one for this data source
        XmlNode yAxis = ex.CreateNew("/plot/yaxis");
        ex.Write(yAxis, "unit", config.Unit);
        ex.Write(yAxis, "color", config.Color);
        yAxisNum = yAxes.Count + 1;
    }

    // Create a new source element under the document root,
    // no matter how many there are already.
    XmlNode source = ex.CreateNew("/plot/source");
    ex.Write(source, "key", codeName);
    ex.Write(source, "yaxis", yAxisNum);
    ex.Write(source, "color/@line", config.Color);
    ex.Write(source, "color/@fill", config.Color);
    ex.Write(source, "color/@opacity", 20);
    ex.Write(source, "smoothing", config.Smoothing);
    ex.Write(source, "avgtime", config.AverageTime);
}

// Access the whole generated XML document string through the Xml property
Clipboard.SetText(ex.Xml);

Download

EasyXml.cs37.3 KiBQuelltext der EasyXml-Klasse

Changes

2015Aug27
  • Read… overloads without a defaultValue parameter throw an exception on missing elements, those with the parameter will return the specified value even when it’s null. (Before, null was not considered a default value and an exception was thrown.)
  • Completed XML documentation.
  • Code cleanup (formatting).

Licence and terms of use

Copying and distribution of this file, with or without modification, are permitted provided the copyright notice and this notice are preserved. This file is offered as-is, without any warranty. (GNU All-Permissive licence)

Statistic data

  • Created on 2011-06-30, updated on 2015-08-27.
  • Ca. 650 lines of code, estimated development costs: 650 - 2 600 €