private void ButtonRequest_Click(object sender, EventArgs e)
{
XmlDocument xml = new XmlDocument();
XmlDocument request = new XmlDocument();
XmlDocument fil = new XmlDocument();
request = xmlRequest1();
fil = xmlFilter();
response = doAvail(request, fil);
XElement po = XElement.Parse(response.OuterXml);
IEnumerable<XElement> childElements = from el in po.Elements() select el;
foreach (XElement el in childElements)
{
ListViewItem item = new ListViewItem(new string[]
{
el.Descendants("Name").FirstOrDefault().Value,
el.Descendants("PCC").FirstOrDefault().Value,
el.Descendants("BusinessTitle").FirstOrDefault().Value,
});
ListViewResult.Items.Add(item);
}
}
ı have an error when i loop to the liesviewitem. please assist,thanks.
You're using FirstOrDefault()
, which will return null
if it doesn't find any values - but you're then unconditionally dereferencing that return value. If you do want to handle the case where you don't get any values, just use a cast to string
instead of the Value
property:
ListViewItem item = new ListViewItem(new string[]
{
(string) el.Descendants("Name").FirstOrDefault(),
(string) el.Descendants("PCC").FirstOrDefault(),
(string) el.Descendants("BusinessTitle").FirstOrDefault(),
});
Now the array will contain a null reference for any missing element. I don't know whether the list view will handle that or not, mind you.
If you don't want to handle the case where the name/pcc/title aren't found, then use First
to make that clear:
ListViewItem item = new ListViewItem(new string[]
{
el.Descendants("Name").First().Value,
el.Descendants("PCC").First().Value,
el.Descendants("BusinessTitle").First().Value,
});
That will currently still give you an exception, of course - just a clearer one. My guess is that you're missing a namespace - that you actually want:
XNamespace ns = "some namespace URL here";
ListViewItem item = new ListViewItem(new string[]
{
el.Descendants(ns + "Name").First().Value,
el.Descendants(ns + "PCC").First().Value,
el.Descendants(ns + "BusinessTitle").First().Value,
});
... but we can't tell what namespace you need without knowing what your XML looks like.
See more on this question at Stackoverflow