Maintaining XSD files in VS2010

Having more-or-less painlessly migrated across to my SSD drive (which is more than can be said for the one I use at work, which randomly wiped itself – even down to the partition itself – after I moved desk last Friday), it’s back to VS2010 stuff. I had to do some work with XSD files … Continue reading Maintaining XSD files in VS2010


A Dynamic XML Document – Part 2

Continuing on from last post, how do we get the array-style [notation] on a dynamic object? Well, there’s a handy method that you can override on DynamicObject called TryGetIndex which does just that: 1: ///

2: /// Searches for any elements that have any attribute with the value specified. 3: /// 4: /// 5: /// 6: /// 7: /// 8: public override bool TryGetIndex (GetIndexBinder binder, object[] indexes, out object result) 9: { 10: var valueToSearchFor = indexes[0].ToString(); 11: var matchingItems = GetElementsByAttributeValue (valueToSearchFor); 12: if (matchingItems.Any ()) 13: { 14: result = new DynamicXmlDocument (matchingItems); 15: return true; 16: } 17: 18: result = null; 19: return false; 20: } 21: 22: private IEnumerable GetElementsByAttributeValue (string attributeValue) 23: { 24: var matchingItems = elements.Where (e => e.Attributes ().Any (att => att.Value == attributeValue)); 25: return matchingItems; 26: } Here, I’m searching for any elements that have any attributes with a value as per specified, and then setting the result to a new dynamic xml document based on that sequence. That’s really it, to be honest! The only things left are the Value getter, which just returns the value of the first element in the dxd, and the implementations of IEnumerable and IEnumerable : - 1: /// 2: /// Gets the contents of the first element in this document. 3: /// 4: public string Value 5: { 6: get { return elements.First ().Value; } 7: } 8: 9: IEnumerator IEnumerable.GetEnumerator () 10: { 11: foreach (var element in this.elements) 12: yield return new DynamicXmlDocument (element); 13: } 14: 15: IEnumerator IEnumerable.GetEnumerator () 16: { 17: foreach (var element in this.elements) 18: yield return new DynamicXmlDocument (element); 19: } I’m not that used to using the yield keyword – to be honest most collections I use day-to-day are the in-built IEnumerable ones, but I see how it’s being used above (this bit is basically taken from here. Anyway… the point being that with a relatively little amount of effort we have an object which can navigate an XML document very easily and more readably than old-style XML access, and with no real loss of type safety compared to those technologies, either.

Dynamic typing with C#4.0 part 2 – A Dynamic XML Document

Here’s a great example of where dynamic typing makes your code much more readable and logical: parsing an xml document. It turns out that someone has already done this – and I nicked a bit of his code (basically the implementation of IEnumerable) - but it’s funny how similar both of our code was before I found it (link is at end of this post). Here’s an example XML document: Gambardella, Matthew XML Developer's Guide Computer 44.95 2000-10-01 An in-depth look at creating applications with XML. Now, to parse that document, you could currently use either good old XmlDocument (and / or XmlReader), or the more modern XDocument in Linq to Xml. However, both of them and still inherently weakly typed, using strings passed into methods such as “Attribute (“MyAttr”) or Element (“MyElement”). I did see an alpha demo of a strongly-typed version of a Xml Document reader a while ago but haven’t heard anything of that recently. I recall seeing that VB9 also has some good XML support, but I’m exclusively a C# coder so let’s concentrate on that 😉 Anyway. So let’s see if we can make an XML document class in C#4 which will let us read the above XML document like this: 1: // Create our dynamic XML document based off a Linq-to-Xml XElement. 2: var xDocument = XDocument.Load ("Example.xml"); 3: dynamic dynamicXmlDocument = new DynamicXmlDocument (xDocument.Root); 4: 5: // Get the first five books 6: var books = as IEnumerable; 7: foreach (dynamic book in books.Take (5)) 8: { 9: // Print out details on each book 10: System.Console.WriteLine ("Id: {0}, Title: {1}, Price: {2}", 11:, // Attribute access 12: book.title.Value, // Element access 13: book.price.Value); // Element access 14: } 15: 16: // Get a specific book 17: var specificBook =["bk107"]; 18: System.Console.WriteLine ("Id: {0}, Title: {1}",, specificBook.title.Value); 19: 20: System.Console.Read (); This actually wasn’t that difficult to write! Again, inheriting from DynamicObject and overriding a couple of methods, I was able to get this done in about three quarters of an hour. First thing is the class hierarchy, our constructors and single member field: 1: class DynamicXmlDocument : DynamicObject, IEnumerable, IEnumerable 2: { 3: IEnumerable elements; 4: 5: ///

6: /// Creates a new instance of the XML Dynamic Document based on a single XElement. 7: /// 8: /// 9: public DynamicXmlDocument (XElement element) 10: { 11: elements = new List { element }; 12: } 13: 14: /// 15: /// Creates a new instance of the XML Dynamic Document based on a sequence of XElements. 16: /// 17: /// 18: public DynamicXmlDocument (IEnumerable elements) 19: { 20: this.elements = new List (elements); 21: } Nothing too scary there, but notice how we implement IEnumerable and IEnumerable so that we can do the foreach and .Take (5) in the original example. The next bit is the first DynamicObject method we override, which gets called every time you make a property accessor request e.g. The method looks for all sub-elements that match the parameter name, and if it finds at least one, returns a new dynamic xml document (dxd) based on them. If not, it looks for any attributes in the first element of the current dxd and returns the value if it finds that. Otherwise it returns null. 1: /// 2: /// Gets either all children the XML Dynamic Documents (i.e. elements), or the current element's attribute. 3: /// 4: /// Specifies the keyword to search on. 5: /// The resultant object. 6: /// True is a match was made. 7: public override bool TryGetMember (System.Dynamic.GetMemberBinder binder, out object result) 8: { 9: var elementNameToSearchFor = binder.Name; 10: var matchingChildElements = elements.Elements (elementNameToSearchFor); 11: if (matchingChildElements.Any()) 12: { 13: result = new DynamicXmlDocument (matchingChildElements); 14: return true; 15: } 16: 17: var attributeNameToSearchFor = binder.Name; 18: var attribute = elements.First ().Attribute (attributeNameToSearchFor); 19: if (attribute != null) 20: { 21: result = attribute.Value; 22: return true; 23: } 24: 25: result = null; 26: return false; 27: } The next question is how to get that array notation e.g. book[“123”] as per the example? That’ll be answered in the next post!