【发布时间】:2012-10-31 16:28:06
【问题描述】:
我需要知道如何将 XML 与我使用的至少一种语言(最好是 WebMatrix C#)一起使用(特别是阅读),但我过去曾多次尝试使用 JavaScript 来做到这一点,但是没有在线示例(在 StackOverflow 或其他方式中)足够完整以使其对我有用(请记住,我没有实际的 XML 经验,我当然已经完成了有关 XPath、XML 等的简单教程,但我们都知道这些教程可以多么简短和不完整)。
我现在想在 WebMatrix C# 中执行此操作,因为在服务器端处理它似乎更易于管理且对用户来说更快。
当我尝试使用此代码使用在线给出的一些示例时:
@using System.Xml.Linq
@{
var file = XDocument.Load(Server.MapPath(@"/App_Code/Test.xml"));
var results = from e in file.Root.Elements()
select new { Name = e.Element("someValue").Value, Sales = e.Element("someValueTwo").Value };
var grid = new WebGrid(results);
}
(我根本不需要使用WebGrid,只是在示例中) 并在 App_Code 文件夹中保存了一个名为 Test.xml 的测试 xml 文档。
尝试从 xml 文档中的两个字段读取一些测试值时出现错误。这是测试xml文档:
<?xml version="1.0" encoding="utf-8" ?>
<someNode>
<someValue>HEY THERE! I'M XML!</someValue>
<someValueTwo>Another Value</someValueTwo>
</someNode>
这里是我尝试在 cshtml 文件中将值调用到页面上的位置:
<p>This should be a fun test!<br/>And the value is...:
@foreach(var f in results)
{
<div>@f.Name</div>
<div>@f.Sales</div>
}
</p>
最后,这是我在运行页面时遇到的错误(请记住,与此测试或使用 xml 相关的其他数据、代码或文件 [cs 或其他] 在我的站点中不存在):
Object reference not set to an instance of an object.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
Source Error:
Line 4: var file = XDocument.Load(Server.MapPath(@"/App_Code/Test.xml"));
Line 5: var results = from e in file.Root.Elements()
Line 6: select new { Name = e.Element("someValue").Value, Sales = e.Element("someValueTwo").Value };
Line 7: var grid = new WebGrid(results);
Line 8: }
(第 6 行是错误所在的行)
我错过了什么?这些例子看起来真的很简单,但是很明显。不是。
老实说,我对 WebMatrix 的了解已经足够多,可以在不使用 XML 的情况下完成我的目标,(我总是可以只使用数据库,或渲染页面等),但我有点厌倦了这种标记语言躲避我,仅仅是因为我永远无法从我使用的任何语言(JavaScript、jQuery、C#)中读取 XML 文件。
【问题讨论】: