Reputation: 97
I have a queue of XML's which are reading via linq as follows: Sample XML
[XML Link](http://www.hattem.nl/roonline/0269/plannen/NL.IMRO.0269.OV165-/NL.IMRO.0269.OV165-VG01/g_NL.IMRO.0269.OV165-VG01.xml)
C# Code
List<String> PlanInfo = new List<string>();
XDocument xdoc = null;
XNamespace ns = null;
try
{
//List<String> PlanValuesList = new List<string>();
xdoc = XDocument.Load(gLink);
ns = xdoc.Root.Name.Namespace;
var test = (
from planInfo in xdoc.Descendants(ns + "Plan").Descendants(ns + "Eigenschappen")
from Onderdelen in xdoc.Descendants(ns + "Onderdelen")
select new
{
Naam = (string)planInfo.Element(ns + "Naam").Value ?? string.Empty,
Type = (string)planInfo.Element(ns + "Type").Value ?? string.Empty,
Status = (string)planInfo.Element(ns + "Status").Value ?? string.Empty,
Datum = (Convert.ToString(planInfo.Element(ns + "Datum").Value).IndexOf("T") > 0) ? (string)planInfo.Element(ns + "Datum").Value.Substring(0, Convert.ToString(planInfo.Element(ns + "Datum").Value).IndexOf("T")) : (string)planInfo.Element(ns + "Datum").Value ?? string.Empty,
Versie = (string)(planInfo.Element("VersieIMRO") ?? planInfo.Element("VersieGML")) ?? string.Empty,//Convert.ToString(planInfo.Element(ns + "VersieIMRO").Value) ?? String.Empty,
VersiePraktijkRichtlijn = (string)planInfo.Element(ns + "VersiePraktijkRichtlijn").Value ?? string.Empty,
BasisURL = (string)Onderdelen.Attribute("BasisURL")
}).ToList();
foreach (var item in test)
{
PlanInfo.Add(item.Naam);
PlanInfo.Add(item.Type);
PlanInfo.Add(item.Status);
PlanInfo.Add(item.Datum);
PlanInfo.Add(item.Versie);
PlanInfo.Add(item.VersiePraktijkRichtlijn);
PlanInfo.Add(item.BasisURL);
}
}
catch (Exception ex)
{
//Error reading GeleideFormulier link for the plan and manifest
throw;//Just throwing error here, as it is catched in the called method.
}
return PlanInfo;
In some XML files "versieIMRO" tag becomes "versieGML", which gives me error as Object Reference Not set to an instance of an object.
Please let me know how to check if there is "versieGML" tag instead of "versieIMRO"? Or if the tag names are different in other XML's, how to deal with it?
Upvotes: 1
Views: 132
Reputation: 89325
You want to cast XElement
to string (not XElement.Value
property which already of type string
), to avoid NRE in case the element is not found :
Version = (string)x.Element("version"),
If you want to use versionX
in case version
element is not found, try this way :
Version = (string)(x.Element("version") ?? x.Element("versionX")),
Once again, casting Value
property to string
on is useless, it doesn't make any difference. If you want to get string.Empty
instead of null
, use null-coalescing operator again :
Version = (string)(x.Element("version") ?? x.Element("versionX")) ?? string.Empty,
Upvotes: 2