[英]Create HTML Table with XML in a asp.net MVC C# Application
我已經計划了一個新的應用程序。 我的想法是生成XML文檔。 我需要一種將XML文檔轉換為HTML表的方法。
我的XML結構是:
<Checklist>
<Title>Titletext</Title>
<Group>
<Title>Active Directory</Title>
<Content>
<Line>
<text type="array">
<value>Connect to:</value>
<value>dsa.msc start</value>
</text>
</Line>
<Line>
<text type="array">
<value>Gruppen anpassen anhand des Arbeitsortes</value>
<value>Profilpfad eintragen</value>
</text>
</Line>
</Content>
</Group>
</Checklist>
我將嘗試將此xml轉換為HTML表,如下所示:
<html>
<table>
<tr class="head">
<td>#Group -> Title</td>
</tr>
<tr class="text">
<td><p>#Line -> Value 1</p><p>@Line -> Value2</p></td>
</tr>
</table>
</html>
我的第一個想法是,逐行讀取XML,並將此值添加到ListArray。 使用foreach,我將嘗試生成HTML
foreach(string item in ViewBag.Content)
有很多“更好”的選擇,還是我應該嘗試通過這種方式解決此問題=)也許有人可以給我一個最佳實踐的提示或其他東西=)
謝謝!
最好的選擇是使用可擴展樣式表語言( XSL )。 您可以使用XSL Tansformations( XSLT )在xml中創建模板,該模板設置了有關如何將XML轉換為另一種格式的規則。 在您的情況下,模板將類似於:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>
<body>
<table border="1">
<tr>
<th><xsl:value-of select="Checklist/Title/Group/Title" /></th>
</tr>
<xsl:for-each select="Checklist/Group/Content/Line">
<tr>
<td>
<xsl:for-each select="Value">
<p><xsl:value-of select="value" /></p>
</xsl:for-each>
</td>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
首先,我將創建一個代表表的一行的類-一個模型。
比起我,我將使用LINQ to XML將xml文件轉換為模型類的對象列表。
比起將模型對象列表放置為View的模型(可以將其強類型化),而不是將其放置到ViewBag中。 在控制器中,您可以通過以下方式返回視圖:
List<MyModel> items = ....
return View(items)
最后,我會像這樣在Razor中進行迭代:
@foreach(var item in Model){ // the Model here is whatever you passed to the View method call in your controller
// create table rows or whatever you need
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.