I’m trying to read a xml file and write it to entities in data model.
The Xml looks like this :
...
<item>
<guid>123456-7890</guid>
<enclosure type="image/jpeg" url="http://example.com"/>
</item>
Sometimes whole enclosure node doesn’t exists, so I’m using let in my query, but it breaks:
var items = from xmlitems in xElem2.Descendants("item")
let node_enclosure = xmlitems.Element("enclosure")
select new
{
strImageUrl = node_enclosure == null ? "none" : node_enclosure.Attribute("url").Value,
strguid = xmlitems.Element("guid").Value,
};
Update: Then I’m trying to save value from xml in Datacontext.
using (var datacontext = new db_RBEntities1())
{
foreach (var item in items)
{
try
{
xmltable = new RSSTable();
xmltable.guid = item.guid;
xmltable.imageurl= item.strImageUrl;
datacontext.RSSTable.AddObject(xmltable);
}
catch (EntitySqlException ex)
{
}
}
datacontext.SaveChanges();
}
Could you help me what’s wrong with my query?
Thanks for your advices!
Regards
I’m not sure what problem you’re having with your code but you can rewrite it to be a little nicer looking (IMHO).
If there’s a possibility that an element may or may not exist in your document and you want to get something from that element, I find it easier to query all elements by that name (expecting there’s only one), project to the value you want (in this case, the value of the
urlattribute) and callSingleOrDefault(). This way, you’ll either get your value or the default value (nullin this case).Also, use casts to read your values from elements or attributes, this makes it less likely to get a
NullPointerExceptionwhen trying to read values.