views:

197

answers:

1

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 --%>
A: 

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":

[XmlRoot(ElementName = "Car", IsNullable = false, Namespace="")]
public class Car
{
    [XmlAttribute(AttributeName = "Model")]
    public string Model { get; set; }
    [XmlAttribute(AttributeName = "Make")]
    public string Make { get; set ;}
}

And here is how to deserialize it properly from a file:

public Car ReadXml(string fileLocation)
{
    XmlSerializer carXml = new XmlSerializer(typeof(Car));

    FileStream fs = File.OpenRead(fileLocation);
    Car result = imageConfig.Deserialize(fs) as Car;

    return result;
}

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:

<!-- It is assumed that MyCar is a public property of the current page. -->
<div>
   Car Model : <%= MyCar.Model %> <br/>
   Car Make : <%= MyCar.Make %>
</div>
Maxim