read xml with linq
I want to read the names form this xml:
<开发者_StackOverflow社区;?xml version="1.0" encoding="utf-8"?>
<string xmlns="http://mysite.com/">
<name>2</name>
<name>3</name>
<name>4</name>
</string>
Tried:
var doc = XElement.Parse(s);
foreach (var v in doc.Descendants("name"))
{
//do work
}
but it does not work. Why?
Because you have a custom namespace - you need to specify the namespace when you select the elements - try this (tested and worked):
XNamespace xmlns = "http://mysite.com/";
var doc = XElement.Parse(s);
foreach (var v in doc.Descendants(xmlns + "name"))
{
//do work
}
精彩评论