1
<Root xmlns="http://tempuri.org/DataSourceSchemaConfig.xsd">
 <Node>
  <Name>Peter</Name>
 </Node>
 <Node>
  <Name>John</Name>
 </Node>
</Root>

How do I get List of Names?

I've was trying this, but it doesn't work, where is my mistake?

            var lists = from node in nodes.Descendants()
                        where node.Name.LocalName.Equals("Node")
                        select node.Elements("Name").First().Value;

L.B SOLUTION WORKS ONLY IF I REMOVE xmlns="http://tempuri.org/DataSourceSchemaConfig.xsd" from my ROOT tag.

4

3 回答 3

5
 XDocument xDoc = XDocument.Load(....);
 var names = xDoc.Descendants("Name").Select(x => x.Value);

- 编辑 -

XDocument xDoc = XDocument.Load(....);
XNamespace ns = XNamespace.Get("http://tempuri.org/DataSourceSchemaConfig.xsd");
var names = xDoc.Descendants(ns+"Name").Select(x => x.Value);
于 2012-05-23T20:30:39.927 回答
1

尝试这个:

var lists = (from node in nodesxml.Root.Descendants("Node")
                     select new
                     {Name = node.Element("Name").Value}).ToList();

其中 nodesxml 是您的 XDocument

于 2012-05-23T20:38:43.500 回答
1

另一个解决方案(不是 LINQ,但可以工作,与命名空间无关):

 XmlDocument doc = new XmlDocument();
 doc.LoadXml(xmlstring);
 XmlNodeList nlist = doc.SelectNodes("/*[local-name(.)='Root']/*[local-name(.)='Node']/*[local-name(.)='Name']/text()");
 var list = new List<string>(nlist.Cast<XmlNode>().Select(x => x.Value));

该 XPath 负责 DefaultNamespace 问题,因为您不能使用 XmlNamespaceManager 来指定默认命名空间。

于 2012-05-23T20:58:08.490 回答