因此,我从数据库中检索XML和XSLT作为字符串,然后使用名为RenderXml
的自定义HTML帮助程序进行渲染。问题是它没有正确渲染。在我的HTML帮助器中,我进行转换
public static HtmlString RenderXml(this HtmlHelper helper, string theXml, string theXslt)
{
XDocument xmlTree = XDocument.Parse(xmlPath);
XDocument newTree = new XDocument();
using (XmlWriter writer = newTree.CreateWriter())
{
// Load the style sheet.
XslCompiledTransform xslt = new XslCompiledTransform();
xslt.Load(XmlReader.Create(new StringReader(xsltPath)));
// Execute the transform and output the results to a writer.
xslt.Transform(xmlTree.CreateReader(), writer);
return new HtmlString(newTree.ToString());
}
}
在我的CSHTML中我这样做
<div id="results">@Html.RenderXml(Model.theXmlFile, Model.theXSLFile,)</div>
当我尝试返回new HtmlString(newTree.ToString());
时,我得到一个空白,当我尝试返回new HtmlString(writer.ToString());
时,我在页面上显示System.Xml.XmlWellFormedWriter
。有谁知道我做错了什么?我从the example here获得了我的代码。我也研究了this one并且除了我不使用URI之外它工作得很好,当我尝试修改它以使用XDocument抱怨缺少参数时,所以我远离它。任何关于他转型的想法都没有用?
答案 0 :(得分:0)
尝试将行return new HtmlString(newTree.ToString());
移到using
块之外:
using (XmlWriter writer = newTree.CreateWriter())
{
// Load the style sheet.
XslCompiledTransform xslt = new XslCompiledTransform();
xslt.Load(XmlReader.Create(new StringReader(xsltPath)));
// Execute the transform and output the results to a writer.
xslt.Transform(xmlTree.CreateReader(), writer);
}
return new HtmlString(newTree.ToString());