我需要知道如何使用(特别是刚读)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可言,它只是在本例中),并保存在命名中的test.xml App_Code文件夹测试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>
最后,这里是我得到的,当我运行的页面(记住,没有其它数据,代码或文件[CS或以其他方式]关于本次测试或使用XML在我的网站的任何地方存在)的错误:
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行是行IT上错误)
我在想什么? 这些例子像真的是这样简单,但OBV。 它不是。
说实话,我已经了解了足够的WebMatrix来完成我的目标,而无需使用XML的,(我总是可以只使用一个数据库,或渲染网页等),但我有点讨厌这种标记语言的无情地躲避我,仅仅是因为我永远不能在任何我使用(JavaScript的,jQuery的,C#)语言的XML文件中读取。