【问题标题】:System.XML Read values into an arraySystem.XML 将值读入数组
【发布时间】:2015-11-19 09:22:53
【问题描述】:

我需要将 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???()
  • 选项text:我选择所有文本值,不关心XPath;
  • 选项XPath:我选择MultiNodePicker/nodeId值;
  • 选项childs:我从所有nodeId子节点中选择值。

【问题讨论】:

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


【解决方案1】:

使用一点 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);
}

【讨论】:

    【解决方案2】:

    使用 LinQ 转 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();
    

    【讨论】:

    • 这应该是 XPath 选项
    猜你喜欢
    • 2012-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-28
    • 2011-08-10
    • 2015-06-10
    • 2011-08-20
    • 1970-01-01
    相关资源
    最近更新 更多