c#
  • .net
  • xml
  • xpath
  • system.xml
  • 2015-11-19 39 views 1 likes 
    1

    我需要閱讀從XML的所有文字值轉換爲列表...了System.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子節點中選擇值。
    +0

    永久鏈接:http://rextester.com/QJTRN53043 – Serge

    回答

    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); 
    } 
    
    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(); 
    
    +0

    這應該是XPath的選擇 – Serge

    相關問題