我需要从C#XDocument中的XML文档中获取信息

时间:2017-09-16 21:19:24

标签: c# .net xml linq

我有XML文档:

<?xml version="1.0" encoding="UTF-8"?>
<routes>
    <route routeNumber = "1">
        <routeName>Route1</routeName>
        <point pointNumber = "1">
            <pointName>Warszawa </pointName>
            <time>10</time>
        </point>
        <point pointNumber = "2">
            <pointName>Gdynia </pointName>
            <time>15</time>
        </point>
    </route>
    <route routeNumber = "1">
        <routeName>Route1</routeName>
        <point pointNumber = "1">
            <pointName>Warszawa </pointName>
            <time>10</time>
        </point>
        <point pointNumber = "2">
            <pointName>Gdynia </pointName>
            <time>15</time>
        </point>
    </route>
</routes>

我有3个班级:

1)Route课程:

public class Route
{
    public int routeNumber { get; set; }
    public string routeName { get; set; }
    List<Point> pointList;

    public Route(int routeNumber, string routeName, list<Point> pointList)
    {
        this.routeNumber = routeNumber;
        this.routeName = routeName;
        this.pointList = pointList;
    }
}

2)Point课程:

public class Point
{
    public int pointNumber { get; set; }
    public string pointName { get; set; }
    public int time { get; set; }

    public Point(int pointNumber, string pointName, int time )
    {
        this.pointNumber = pointNumber;
        this.pointName = pointName;
        this.time = time;
    }
}

3)XmlReader课程:

public XmlReader
{
    public List<Route> GetXml()
    {
        XDocument xml = XDocument.Load("dane.xml");
        List<Route> route = (
            from route in xml.Root.Elements("route")
            select new Route(
                int.Parse(route.Attribute("routeNumber").Value),
                route.Element("routeName").Value
            ).ToList<Route>();
        return route;
    }
}

当我们从班级Route移出积分列表时,我的方法GetXml会返回包含其名称和号码的路线列表。但我需要为每条路线获取Points的列表,包括点数,点的名称和时间。我怎么能这样做?

我将XmlReader clas编辑为:

public XmlReader
{
    public List<Route> GetXml()
    {
        XDocument xml = XDocument.Load("dane.xml");
        List<Route> route = (
            from route in xml.Root.Elements("route")
            select new Route(
                int.Parse(route.Attribute("routeNumber").Value),
                route.Element("routeName").Value,
                    (
                       from point
                       in
                             xml
                             .Descendants()
                             .Elements("point")
                       select new Point(
                            int.Parse(point.Attribute("pointNumber").Value),
                            point.Element("pointName").Value,
                            int.Parse(point.Element("time").Value)
                            )
                        ).ToList<Point>()
            ).ToList<Route>();
        return route;
    }
}

但现在我在路线上获得了所有积分的清单。如何更改代码以仅获取每条路线中一条路线的点列表?

0 个答案:

没有答案