XML解析到多个列表

时间:2016-12-21 02:25:20

标签: c# xml xml-parsing

我想将保存的xml加载到特定列表中。目前,它只是加载2个SceneObjects。我不是100%确定正确构造的xml文件或此时的代码。如果有人能够指出我正确的方向,我会很感激。我已经研究过可能将3个类合并为1来创建xml以及其他一些可能性(linq),这些可能性在我的编码级别之后有点超出我的编码水平。我正在写项目来学习我的能力。谢谢! XML和代码如下。

代码:

private void btnOpenFile_Click(object sender, EventArgs e)
        {
            Stream myStream = null;
            OpenFileDialog openFileDialog1 = new OpenFileDialog();

            openFileDialog1.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
            openFileDialog1.Filter = "XML Files (*.xml)|*.*";
            openFileDialog1.FilterIndex = 1;
            openFileDialog1.RestoreDirectory = true;

            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    if ((myStream = openFileDialog1.OpenFile()) != null)
                    {
                        using (myStream)
                        {
                            //create the XmlReaderSettings object
                            XmlReaderSettings settings = new XmlReaderSettings();
                            settings.IgnoreWhitespace = true;
                            settings.IgnoreComments = true;

                            //create the xml reader object
                            XmlReader xmlIn = XmlReader.Create(myStream, settings);

                            //read past all nodes until the first SceneObject node
                            if (xmlIn.ReadToDescendant("SceneObject"))
                            {
                                //create one waypoint object for each node
                                do
                                {
                                    SceneObject sceneObject = new SceneObject();

                                    xmlIn.ReadStartElement("SceneObject");
                                    sceneObject.RunMethod = xmlIn.ReadElementContentAsString();
                                    sceneObject.Name = xmlIn.ReadElementContentAsString();
                                    sceneObject.Paint = xmlIn.ReadElementContentAsString();
                                    sceneObject.Latitude = xmlIn.ReadElementContentAsDouble();
                                    sceneObject.Longitude = xmlIn.ReadElementContentAsDouble();
                                    sceneObject.Altitude = xmlIn.ReadElementContentAsInt();
                                    sceneObject.Pitch = xmlIn.ReadElementContentAsDouble();
                                    sceneObject.Bank = xmlIn.ReadElementContentAsDouble();
                                    sceneObject.Heading = xmlIn.ReadElementContentAsDouble();
                                    sceneObject.OnGround = Convert.ToByte(xmlIn.ReadElementContentAsString());
                                    sceneObject.Airspeed = Convert.ToUInt32(xmlIn.ReadElementContentAsString());

                                    sceneObjectList.Add(sceneObject);
                                }
                                while (xmlIn.ReadToNextSibling("SceneObject"));
                            }

                            //read past all nodes until the first Waypoint node
                            if (xmlIn.ReadToDescendant("Waypoint"))
                            {
                                //create one waypoint object for each node
                                do
                                {
                                    Waypoint waypoint = new Waypoint();

                                    xmlIn.ReadStartElement("Waypoint");
                                    waypoint.Id = xmlIn.ReadElementContentAsInt();
                                    waypoint.Flags = Convert.ToUInt32(xmlIn.ReadElementContentAsString());
                                    waypoint.Latitude = xmlIn.ReadElementContentAsDouble();
                                    waypoint.Longitude = xmlIn.ReadElementContentAsDouble();
                                    waypoint.Altitude = xmlIn.ReadElementContentAsDouble();
                                    waypoint.Speed = xmlIn.ReadElementContentAsDouble();
                                    waypoint.Count = xmlIn.ReadElementContentAsInt();

                                    wayPointList.Add(waypoint);
                                }
                                while (xmlIn.ReadToNextSibling("Waypoint"));
                            }

                            //read past all nodes until the first FlightPlan node
                            if (xmlIn.ReadToDescendant("FlightPlan"))
                            {
                                //create one flightplan object for each node
                                do
                                {
                                    FlightPlan flightPlan = new FlightPlan();

                                    xmlIn.ReadStartElement("FlightPlan");
                                    flightPlan.Name = xmlIn.ReadElementContentAsString();
                                    flightPlan.Paint = xmlIn.ReadElementContentAsString();
                                    flightPlan.Flight = xmlIn.ReadElementContentAsString();

                                    flightPlanList.Add(flightPlan);
                                }
                                while (xmlIn.ReadToNextSibling("FlightPlan"));
                            }
                            xmlIn.Close();
                        }
                    }
                }

                catch (Exception ex)
                {
                    MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message, "FlighT");
                }
            }
        }

XML:

 <?xml version="1.0" encoding="utf-8"?>
<Scene>
    <SceneObjects>
        <SceneObject>
            <RunMethod>AICreateSimulatedObjectVehicle</RunMethod>
            <Name>Veh_Air_BagTractor_Euro_White_sm</Name>
            <Paint />
            <Latitude>55.3579907547104</Latitude>
            <Longitude>-131.714398095813</Longitude>
            <Altitude>92</Altitude>
            <Pitch>0</Pitch>
            <Bank>0</Bank>
            <Heading>111</Heading>
            <Onground>1</Onground>
            <Airspeed>0</Airspeed>
        </SceneObject>
        <SceneObject>
            <RunMethod>AICreateSimulatedObjectVehicle</RunMethod>
            <Name>VEH_Air_BagLoaderGrey</Name>
            <Paint />
            <Latitude>55.3579907547104</Latitude>
            <Longitude>-131.714398095813</Longitude>
            <Altitude>92</Altitude>
            <Pitch>0</Pitch>
            <Bank>0</Bank>
            <Heading>111</Heading>
            <Onground>1</Onground>
            <Airspeed>0</Airspeed>
        </SceneObject>
    </SceneObjects>
    <Waypoints>
        <Waypoint>
            <Id>1</Id>
            <Flags>4</Flags>
            <Latitude>55.3579907547104</Latitude>
            <Longitude>-131.714398095813</Longitude>
            <Altitude>92</Altitude>
            <Speed>12</Speed>
            <Count>0</Count>
        </Waypoint>
        <Waypoint>
            <Id>1</Id>
            <Flags>4</Flags>
            <Latitude>55.3579907547104</Latitude>
            <Longitude>-131.714398095813</Longitude>
            <Altitude>92</Altitude>
            <Speed>12</Speed>
            <Count>1</Count>
        </Waypoint>
    </Waypoints>
    <FlightPlans>
        <FlightPlan>
            <Name>Beech_King_Air_350</Name>
            <Paint>Beech King Air 350 Paint1</Paint>
            <Flight>IFR Ketchikan Intl to Annette Island</Flight>
        </FlightPlan>
    </FlightPlans>
</Scene>

3 个答案:

答案 0 :(得分:0)

您是否考虑过使用AutoMapper

Scott Toberman提供了一个很好的codeplex tutorial,它表明您可以将XML映射到列表。这是一个有点过时,但给出一个很好的概述。 Stan Bashtavenko的另一个here可能会有所帮助。

另一条路径是使用XSD.exe工具使用c#序列化来生成ckarras建议的所需对象结构和XML架构。

答案 1 :(得分:0)

根据创建列表的目的,您可能会发现使用DataTables会更好。 DataSet将加载/写入您的xml文件,将数据存储在DataTables中。一旦进入数据表,您就可以按照您希望,编辑,显示等方式处理数据。

答案 2 :(得分:0)

您可以按照这个简单的步骤进行操作

1.Please Add using System.Xml as a reference;
2.Make a class named book in this way



     public class book
            {
                public Nullable<System.DateTime> date{ get; set; }
                public decimal price { get; set; }
                public string title { get; set; }
                public string description { get; set; }
        }

    try
                {
                    XmlDocument xmlDoc = new XmlDocument();
                    xmlDoc.Load("Write down full path");
                    XmlNodeList dataNodes = xmlDoc.SelectNodes("/catalog");

                    foreach (XmlNode node in dataNodes)
                    {
                        book objbook = new book();
                     objbook.date=Convert.ToDateTime(node.Attributes["date"].Value);
                       objbook.title=node.SelectSingleNode("title").InnerText;
                   objbook.description=node.SelectSingleNode("description").InnerText;
objbook.price=Convert.ToDecimal(node.SelectSingleNode("price").InnerText);

                    }

                }
catch(Exception ex)
{
throw ex;
}

这里我使用一个类,你可以创建另一个类。在序列化时,然后将序列化数据分配给两个类的对象。