如何从Razor中的模型中读取xml字符串

时间:2014-12-11 11:23:07

标签: c# xml razor

我在razor中有一个现有的.net应用程序渲染数据,我想使用razor从每个记录的XML字符串中显示一个特定的节点。但我不知道如何写它。模型中将有50多条记录,因此我想确保它的效率。

模型中的每条记录都有自己的xmldata。例如:


型号:

namespace Project.Web.ViewModels
{  
   public class SampleModel  
   {  
      public int id { get; set; }  
      public string xmldata { get; set; }  
   }  
}


第一记录的xmldata:

<content>
  <user>
    <firstname>Jim</firstname>
    <lastname>Smith</lastname>
  </user>
</content>


xmldata第二条记录:

<content>
  <user>
    <firstname>John</firstname>
    <lastname>Jones</lastname>
  </user>
</content>


CSHTML:

@model Project.Web.ViewModels.SampleModel
@foreach (item in Model) {
   <p><b>ID:</b> @item.id</p>
   <p><b>FirstName:</b> //Add firstname from @item.xmldata here</p>
   <p><b>LastName:</b> //Add lastname from @item.xmldata here</p>
   <br>
}


期望的输出:

ID: 1
FirstName: Jim
LastName: Smith

ID: 2
FirstName: John
LastName: Jones

如何用cshtml编写剃刀代码的例子将非常感谢!

1 个答案:

答案 0 :(得分:0)

这种方法怎么样:

 using System.Xml.Linq;
 public class SampleModel
 {
     private XDocument document;

     public int Id {get;set;}

     public string FirstName 
     {
         get { return document.Descendants("firstname").Single().Value; }
     }

     // other properties in the same manner

     // Dynamic
     public string GetData(string fieldName)
     { 
        return document.Descendants(fieldname).Single().Value;
     }

     public SampleModel(){}
     public SampleModel(int id, string xml)
     {
        this.Id = id;
        this.document = XDocument.Parse(xml);
     }


 }

并在视图中

@model IEnumerable<Project.Web.ViewModels.SampleModel>
@foreach (item in Model) {
   <p><b>ID:</b> @item.id</p>
   <p><b>FirstName:</b> @item.GetData("firstname")</p>
   <p><b>LastName:</b> @item.GetData("lastname")</p>
   <br>
}