I have this XML in a column in my table:
<keywords> <keyword name='First Name' value='|FIRSTNAME|' display='Jack' /> <keyword name='Last Name' value='|LASTNAME|' display='Jones' /> <keyword name='City' value='|CITY|' display='Anytown' /> <keyword name='State' value='|STATE|' display='MD' /> </keywords>
I’m getting a record out of that table using LINQ to SQL via this:
GeneratedArticle ga = db.GeneratedArticles.Single(p => p.GeneratedArticleId == generatedArticleId);
That works, I get my GeneratedArticle object just fine.
I’d like to walk through the data in the ArticleKeywords field, which is XML. I started doing this:
var keywords = from k in ga.ArticleKeywords.Elements('Keywords') select k; foreach (var keyword in keywords) { //what goes here? }
I’m not 100% sure that I’m getting that data correctly. I need help with the proper syntax to get the value and display out of my XML field.
Here is a sample code:
To read keywords we need to call Elements(‘keyword‘) not Elements(‘keywords‘) since keywords is a root node.
You can get attribute value using foo.Attribute(‘bar’).Value, but this method would throw exception if attribute is missing. Safe way to get attribute value is (string)foo.Attribute(‘bar’) – it will give you null if attribute is missing