如何将Web UI绑定到XML属性?
时间:2020-03-06 14:43:04 来源:igfitidea点击:
我想将UI绑定到网页上的XElement及其属性的集合。假设地,这可以用于表示XML树的任何对象。我希望可能会有更好的方法。
我是否应该使用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 --%>
解决方案
我通常使用带有[XmlRoot],[XmlElement],[XmlAttribute]的"占位符"类,并将xml传递给反序列化器,该反序列化器为我提供了占位符类型的对象。完成此操作后,剩下要做的就是对强类型对象进行一些基本的DataBinding。
这是一个"启用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; }
当然,我们可以将MemoryStream替换为FileStream,以直接从内存中读取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>