System.XML将值读入数组

时间:2015-11-19 09:22:54

标签: c# .net xml xpath system.xml

我需要将XML中的所有文本值读入列表...

我的XML格式如下:

<MultiNodePicker type="content">
  <nodeId>52515</nodeId>
  <nodeId>52519</nodeId>
</MultiNodePicker>

我的代码:

string mystring= @"<MultiNodePicker type='content'>
  <nodeId>52515</nodeId>
  <nodeId>52519</nodeId>
</MultiNodePicker>";
var doc = new XmlDocument();
doc.LoadXml(mystring);
Console.WriteLine(doc.InnerText);  
List<string> ids = doc.GetTextValues???()
  • 选项文字:我选择所有文字值,不关心XPath;
  • 选项 XPath :我选择MultiNodePicker/nodeId值;
  • 选项孩子:我从所有nodeId子节点中选择值。

2 个答案:

答案 0 :(得分:2)

使用一点LINQ:

var ids = XElement.Parse(mystring)
    .Descendants("nodeId")
    .Select(x => x.Value); // or even .Select(x => int.Parse(x.Value));

foreach(var id in ids) {
    Console.WriteLine(id);
}

答案 1 :(得分:0)

使用LinQ to XML:

string mystring = @"<MultiNodePicker type='content'>
<nodeId>52515</nodeId>
<nodeId>52519</nodeId>
</MultiNodePicker>";
var doc = new XmlDocument();
doc.LoadXml(mystring);
List<string> memberNames = XDocument.Parse(mystring)
.XPathSelectElements("//MultiNodePicker/nodeId")
.Select(x => x.Value)
.ToList();