从调试我可以检查Stream正在传递
<POS>
<Id>4</Id>
<FolderPath>C://FolderPath</FolderPath>
<Number>44</Number>
<POSTillTypeRecord>Tilltype</POSTillTypeRecord>
<StockLocationRecord>StockLocationRec</StockLocationRecord>
</POS>
为:
public XmlActionResult Upload()
{
//List<POSUnitRecord> POSs = null;
try
{
using (var up = new StreamReader(Request.InputStream))
{
POSUnitRecord POS =
(
from e in XDocument.Load(up).Root.Elements("Payment") //POS")
//select (string)e.Element("POS")
select new POSUnitRecord
{
Id = Int32.Parse((string)e.Element("Id")),
FolderPath = (string)e.Element("FolderPath"),
Number = Int32.Parse((string)e.Element("Number")),
//POSTillTypeRecord = (string)e.Element("POSTillTypeRecord"),
//StockLocationRecord = (string)e.Element("StockLocationRecord")
}
).FirstOrDefault();
为什么POSUnitRecord POS返回NULL。付款/ POS有什么关系?
答案 0 :(得分:1)
您的XML在root下没有Payment
个元素。所以你有空序列。从空序列中获取FirstOrDefault()
会为您提供null
。
我建议您直接将xml加载到XElement中:
var p = XElement.Load(reader);
var pos = new POSUnitRecord
{
Id = (int)p.Element("Id"),
FolderPath = (string)p.Element("FolderPath"),
Number = (int)p.Element("Number")
};
附注 - 您可以在此处使用Xml序列化:
[XmlRoot("POS")]
public class POSUnitRecord
{
public int Id { get; set; }
public string FolderPath { get; set; }
public int Number { get; set; }
}
反序列化很简单:
using (var reader = new StreamReader(Request.InputStream))
{
XmlSerializer serializer = new XmlSerializer(typeof(POSUnitRecord));
var pos = (POSUnitRecord)serializer.Deserialize(reader);
}
答案 1 :(得分:0)
您选择的“付款”元素不存在,但有一个“POS”元素。此外,该元素变为Root
。最后,不需要使用Linq语法;您可以使用XLinq提供的方法:
var xDoc = XDocument.Load(up);
var posUnitRecords = xDoc.Root.Select(e => new POSUnitRecord()
{
Id = Int32.Parse((string)e.Element("Id").Value),
FolderPath = (string)e.Element("FolderPath").Value,
Number = Int32.Parse((string)e.Element("Number").Value),
});
var firstRecord = POSUnitRecords.First();