Linq to Xml, '+' operation inside query expression
-
25-05-2021 - |
Question
var query = from k in xDoc.Descendants("product")
select
new
{
KategoriKod =Convert.ToString( k.Element("cat1").Value) + Convert.ToString( k.Element("cat2").Value),
};
I want to take two elemens of an xml file by one variable. but I recieve this Error
"'string' does not contain a definition for 'Value' "
any one help plz.?
La solution
The following works for me:
static void Main(string[] args)
{
var xDoc = XDocument.Parse(
@"<root>
<product>
<cat1>ABC</cat1>
<cat2>123</cat2>
</product>
<product>
<cat1>XYZ</cat1>
</product>
</root>");
var query = from k in xDoc.Descendants("product")
select new
{
KategoriKod = (string)k.Element("cat1") + (string)k.Element("cat2")
};
foreach(var k in query)
{
Console.WriteLine(k);
}
}
Here is the result:
{ KategoriKod = ABC123 } { KategoriKod = XYZ } Press any key to continue . . .
Note that I used explicit conversion operator (casting elements to string) to avoid NullReferenceExceptions in when calling .Value on elements that do not exist.
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow