📜 ⬆️ ⬇️

Use dynamic to quickly create xml

Not so long ago, I developed a functional that forms various xml by some algorithm.
It is logical that when writing the first test, the traditional question of a lazy programmer arose: how to save my strength, and the nerve reader and quickly and visually imagine what I want to get?
Therefore, I came up with this way:

Example


dynamic rootTag = new XmlBuilder("Root", _nmsps); dynamic modelTag = new XmlBuilder("Model", _nmsps); dynamic elementTag = new XmlBuilder("ElementRef", _nmsps); dynamic attrTag = new XmlBuilder("ElementAttribute", _nmsps); XDocument doc = rootTag(id: Guid.Empty, model: modelTag(id: model.ObjectId, name: model.Name, e1: elementTag(id: er.ObjectId, name: elem1.Name, ea1: attrTag(id: attr1.ObjectId, name: attr1.Name), ea2: attrTag(id: attr2.ObjectId, name: attr2.Name)), e2: elementTag(id: er2.ObjectId, name: elem2.Name))); 

XmlBuilder is a self-written class inheriting from DynamicObject.
To create a document, it is called as a method and converts the arguments either to attributes based on the parameter name - if it is an argument of any type except XmlBuilder - or to the child elements (the parameter name is not important here) - if it is XmlBuilder.
In addition, each XmlBuilder represents a certain tag in the resulting document.

In the test, we compare what we need with what we have obtained using an uncomplicated comparator; as a result, this test looks something like this:

 //     //... // ,     dynamic rootTag = new XmlBuilder("Root", _nmsps); dynamic modelTag = new XmlBuilder("Model", _nmsps); dynamic elementTag = new XmlBuilder("ElementRef", _nmsps); dynamic attrTag = new XmlBuilder("ElementAttribute", _nmsps); XDocument targetDocument = rootTag(id: Guid.Empty, model: modelTag(id: model.ObjectId, name: model.Name, e1: elementTag(id: er.ObjectId, name: elem1.Name, ea1: attrTag(id: attr1.ObjectId, name: attr1.Name), ea2: attrTag(id: attr2.ObjectId, name: attr2.Name)), e2: elementTag(id: er2.ObjectId, name: elem2.Name))); // var resultDocument = TestableMethod(); // var _comparer = new XDocComparer(); Assert.IsTrue(_comparer.Equals(targetDocument, resultDocument)); 

')
For simplicity, I had to donate unnecessary opportunities for me (declarations, for example).
Well, the comparator, due to the fact that it is an IEqualityComparer, does not show what exactly does not match, but only the final result.

However, the implementation of XmlBuilder is here , and the implementation of XDocComparer is here , please use if it can be useful to someone.

Source: https://habr.com/ru/post/175051/


All Articles