【问题标题】:XML Parse to Multiple ListXML 解析为多个列表
【发布时间】:2017-05-06 08:49:38
【问题描述】:

我想将保存的 xml 加载到特定列表中。目前,它只是加载了 2 个场景对象。在这一点上,我不能 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>

【问题讨论】:

  • 为什么不使用 XML 序列化。您可以使用几行清晰的代码反序列化此 XML
  • 谢谢,我会查查的。

标签: c# xml xml-parsing


【解决方案1】:

您是否考虑过使用AutoMapper

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

另一种方法是使用 C# 序列化,使用 XSD.exe 工具生成 ckarras 建议的所需对象结构和 XML 架构。

【讨论】:

  • 看起来有几种方法可以做到这一点,我会开始努力的。谢谢!
【解决方案2】:

根据创建列表的目的,您可能会发现使用 DataTables 会更好。 DataSet 将加载/写入您的 xml 文件,将数据存储在 DataTables 中。进入 Datables 后,您可以根据需要对数据进行操作、编辑、显示等。

【讨论】:

    【解决方案3】:

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

    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;
    }
    

    这里我用一个类,你可以做另一个类。序列化时,将序列化后的数据赋值给两个类的对象。

    【讨论】:

      猜你喜欢
      • 2017-01-29
      • 1970-01-01
      • 2014-12-25
      • 2020-03-15
      • 2021-08-21
      • 1970-01-01
      • 2015-04-13
      • 2017-11-07
      • 1970-01-01
      相关资源
      最近更新 更多