Reputation: 419
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
Upvotes: 1
Views: 727
Reputation: 3919
i try it works xml file
<?xml version="1.0" encoding="utf-8" ?>
<items>
<item>
<guid>123458-7890</guid>
</item>
<item>
<guid>123456-7890</guid>
<enclosure type="image/jpeg" url="http://example.com"/>
</item>
</items>
code to get xelement
XElement xElem2 = XElement.Load(@"C:\\XMLFile1.xml");
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
};
Upvotes: 0
Reputation: 134881
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 url
attribute) and call SingleOrDefault()
. This way, you'll either get your value or the default value (null
in this case).
Also, use casts to read your values from elements or attributes, this makes it less likely to get a NullPointerException
when trying to read values.
var items =
from item in doc.Descendants("item")
let enclosureUrl = item.Elements("enclosure")
.Select(enclosure => (string)enclosure.Attribute("url"))
.SingleOrDefault()
select new
{
Guid = (string)item.Element("guid"),
Url = enclosureUrl ?? "none",
};
Upvotes: 3