Reputation: 4747
I'm trying to parse a visual studio resource file that contains various translated strings like so:
<data name="InvalidGroupType" xml:space="preserve">
<value>La sélection du type de groupe n'est pas valide.</value>
</data>
<data name="ProgressFailure" xml:space="preserve">
<value>Liste des échecs</value>
</data>
<data name="Loronix" xml:space="preserve">
<value>Loronix</value>
</data>
<data name="InputString" xml:space="preserve">
<value>Entrée</value>
</data>
As well as other stuff. I just want the data name and value strings.
I tried to parse this file line by line using the following:
StreamReader fileMain = new StreamReader(MainFile);
while ((line = fileMain.ReadLine()) != null)
{
string data = checkForData(line); --checks each line for "<data name="
if( data.Length > 0)
StringsToTranslatelist.Add(data);
}
But I guessed there must be a better way to do this. So I used a LINQ like so:
XDocument xDoc = XDocument.Load(resxFile);
var result = from item in xDoc.Descendants("data")
select new
{
Name = item.Attribute("name").Value,
Value = item.Element("value").Value
};
foreach (var entry in result)
{
string name = entry.Name;
string value = entry.Value;
//Do somethign here
}
THe problem is that when I get to my foreach loop I get an exception or: "An unhandled exception of type 'System.NullReferenceException' occurred in MyProgram.exe. Object reference not set to an instance of an object"
Does anyone know why?? Am I using the LINQ correctly
Upvotes: 1
Views: 884
Reputation: 236188
Looks like some data
element do not have name
attribute or value
element. To avoid this - use casting instead of accessing Value
property. Otherwise you will receive NullReferenceException
if either name
attribute or value
element is not found
var result = from item in xDoc.Descendants("data")
select new {
Name = (string)item.Attribute("name"),
Value = (string)item.Element("value")
};
Another possible reason is namespace issue. But default resource files do no have namespaces defined.
Upvotes: 2