开发者

read xml with linq

开发者 https://www.devze.com 2023-03-04 06:42 出处:网络
I want to read the names form this xml: <开发者_StackOverflow社区;?xml version=\"1.0\" encoding=\"utf-8\"?>

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
}
0

精彩评论

暂无评论...
验证码 换一张
取 消