0

I want to get the 3rd node of a branching node. Example

<rows>
    <row>
        <cell>a</cell>
        <cell>b</cell>
        <cell>c</cell>
        <cell>d</cell>
        <cell>e</cell>
        <cell>f</cell></row>
    <row>
        <cell>aa</cell>
        <cell>bb</cell>
        <cell>cc</cell>
        <cell>dd</cell>
        <cell>ee</cell>
        <cell>ff</cell>
    </row>
......
</rows>

I basically want to get item c and cc and so on out. Basically the third cell element in rows. This is what i have. However what i want are the values of the items not the xml.

var Study = XDocument.Load(XmlReader.Create(studyStream));

var rows = Study.Descendants("row");
foreach (var item in rows)
{
    var cells = item.Descendants("cell");
    string id = null;
    foreach (var items in cells)
    {
        id = items.Parent.FirstNode.NextNode.NextNode.ToString();
    }

    Console.WriteLine(id);
}

Console.Read();

Is there a way to do this properly? Thank you for all your help.

Kevin

4

2 回答 2

0

好吧,您可以执行以下操作:

var xdoc = XDocument.Load(@"your_file.xml");
foreach (var children in xdoc.XPathSelectElements("rows/row"))
{
    var thirdChild = children.Elements().Skip(2).Take(1).FirstOrDefault();
    if (thirdChild != null)
        Console.WriteLine(thirdChild.Value);
}

在这里,我们首先选择/row元素,然后为每个这样的行选择第三个孩子的值。

这个有价值的集合也可以在没有foreach循环的情况下获得,只能通过 linq 查询,如:

var values = xdoc.XPathSelectElements("rows/row")
                 .Select(row => row.Elements().Skip(2).Take(1).First().Value);
于 2015-09-25T10:44:02.607 回答
0

你也可以这样做

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string input =
                "<rows>" +
                    "<row>" +
                        "<cell>a</cell>" +
                        "<cell>b</cell>" +
                        "<cell>c</cell>" +
                        "<cell>d</cell>" +
                        "<cell>e</cell>" +
                        "<cell>f</cell></row>" +
                    "<row>" +
                        "<cell>aa</cell>" +
                        "<cell>bb</cell>" +
                        "<cell>cc</cell>" +
                        "<cell>dd</cell>" +
                        "<cell>ee</cell>" +
                        "<cell>ff</cell>" +
                    "</row>" +
                "</rows>";

            XElement rows = XElement.Parse(input);

            var results = rows.Descendants("row").Select(x => new
            {
                cells = x.Elements("cell").Select(y => y.Value).ToList()
            }).ToList();

            List<string> thirdCells =  results.Select(x => x.cells[2]).ToList();

        }
    }
}
​
于 2015-09-25T12:56:33.560 回答