2008-09-25 19 views
0

我想將我的UI綁定到XElements集合及其在網頁上的屬性。假設,這可能是任何代表XML樹的對象。我希望可能有更好的方法來做到這一點。如何根據XML屬性綁定Web UI?

我應該使用XPath查詢來獲取集合中的元素以及每個(在本例中)XElement的屬性值嗎?是否有一種對象旨在簡化針對XML的數據綁定?

<% foreach(var x in element.Descendants()) 
    {%> 
<%= DateTime.Parse(x.Attribute["Time"]).ToShortDate() %> 
<% } %> 
<%-- excuse me, I just vomited a little in my mouth --%> 

回答

0

我通常使用與[XmlRoot]一個「佔位符」類,[的XmlElement],[XmlAttribute]和予有傳遞到解串器,其使我有佔位符的類型的對象的XML。一旦完成,剩下的唯一事情就是對強類型對象進行一些基本的數據綁定。

下面是一個簡單的類,是「支持XML」:

[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 ;} 
} 

這裏是如何從一個文件中正確反序列化:

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; 
} 

當然,你可以更換的FileStream由MemoryStream直接從內存中讀取Xml。

一旦在HTML,它會轉化爲這樣的事情:

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