为什么非空XElements导致NRE?

时间:2015-01-08 18:13:57

标签: c# linq-to-xml extension-methods ienumerable xelement

当我将XElements传递给数据时,为什么我的扩展方法 GetVendorForXMLElement()在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()调用看到的:

enter image description here

无论对&#34;选择(GetVendorForXMLElement)&#34;的三种类型的调用中的哪一种;我用,NRE发生。它是CompanyName元素中的尖括号(&#34; [blank]&#34;)?或... ???

1 个答案:

答案 0 :(得分:3)

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