【发布时间】:2015-03-06 23:07:41
【问题描述】:
为什么我的扩展方法 GetVendorForXMLElement() 在我将 XElements 与数据一起传递给 NRE 时会在 NRE 中爆发?
相同的代码(除了使用的自定义类,这里是“供应商”)适用于其他类/数据,但不是在这里。我在 GetVendorForXMLElement() 方法中得到一个 NRE。
private void buttonVendors_Click(object sender, EventArgs e)
{
IEnumerable<Vendor> vendors = GetCollectionOfVendors();
}
private IEnumerable<Vendor> GetCollectionOfVendors()
{
ArrayList arrList = FetchDataFromServer("http://localhost:21608/api/vendor/getall/dbill/ppus/42");
String contents = "<Vendors>";
foreach (String s in arrList)
{
contents += s;
}
contents += "</Vendors>";
String unwantedPreamble = "<ArrayOfVendor xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns=\"http://schemas.datacontract.org/2004/07/CStore.DomainModels.HHS\">";
contents = contents.Replace(unwantedPreamble, String.Empty);
contents = contents.Replace("</ArrayOfVendor>", String.Empty);
MessageBox.Show(contents);
XDocument xmlDoc = XDocument.Parse(contents);
// The result (NRE) is the same with any one of these three "styles" of calling Select()
//IEnumerable<Vendor> vendors = xmlDoc.Descendants("Vendor").Select(GetVendorForXMLElement).ToList();
//IEnumerable<Vendor> vendors = xmlDoc.Descendants("Vendor").Select(x => GetVendorForXMLElement(x));
IEnumerable<Vendor> vendors = xmlDoc.Descendants("Vendor").Select<XElement, Vendor>(GetVendorForXMLElement);
return vendors;
}
private static Vendor GetVendorForXMLElement(XElement vendor)
{
return new Vendor
{
CompanyName = vendor.Element("CompanyName").Value,
VendorID = vendor.Element("VendorID").Value
};
}
public class Vendor
{
public String CompanyName { get; set; }
public String VendorID { get; set; }
public String siteNum { get; set; }
}
有有数据;这是我在 XDocument.Parse() 调用之前使用 MessageBox.Show() 调用看到的:
无论我使用对“Select(GetVendorForXMLElement)”的三种调用中的哪一种,都会发生 NRE。是 CompanyName 元素中的尖括号(“[空白]”)吗?还是……???
【问题讨论】:
-
您是否尝试过将 LINQ 查询拆分为多个部分并分别调试每个部分?
-
你能显示堆栈跟踪吗?此外,
GetVendorForXMLElement不是 扩展方法。只是一个静态方法。
标签: c# linq-to-xml extension-methods ienumerable xelement