为什么 non-null XElements 会导致 NRE?

Why do non-null XElements cause an NRE?

为什么我的扩展方法 GetVendorForXMLElement() 在我向它传递带有数据的 XElements 时在 NRE 中爆发?

相同的代码(除了使用的自定义 class,此处为 "Vendor")适用于其他 classes/data,但不适用于此处。我在 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 元素中的尖括号(“[空白]”)吗?或者...???

您的元素有一个 VendorId 元素,而不是 VendorID 元素(注意大小写),Element("VendorID") 因此 returns null,并调用 Value 抛出 NRE。