I want to bind my UI against a collection of XElements and their properties on a webpage. Hypothetically, this could be for any object that represents an XML tree. I’m hoping that there might be a better way of doing this.
Should I use an XPath query to get out the elements of the collection and the attribute values of each (in this case) XElement? Is there a type of object that is designed to ease databinding against XML?
<% foreach(var x in element.Descendants()) {%> <%= DateTime.Parse(x.Attribute['Time']).ToShortDate() %> <% } %> <%-- excuse me, I just vomited a little in my mouth --%>
I normally use a ‘placeholder’ class with [XmlRoot], [XmlElement], [XmlAttribute] and I have the xml passed to a deserializer which gives me an object of the type of the placeholder. Once this is done, the only thing left to do is some basic DataBinding to a strongly typed object.
Here is a sample class that is ‘Xml Enabled’:
And here is how to deserialize it properly from a file:
Of course, you could replace the FileStream by a MemoryStream to read the Xml directly from memory.
Once in the Html, it would translate to something like this: