winforms 将文本框中输入的值保存到xml文件

cgfeq70w  于 2022-11-17  发布在  其他
关注(0)|答案(2)|浏览(165)

我是XML新手,我试着创建一个窗口窗体来收集每个教师、学生、操作员和技术人员的编号、姓名和级别。但是这个代码太长了。你有什么建议用c#创建这个XML吗?每个雇员的编号、姓名和级别的信息将从4个文本框中获取。另外,描述也将从文本框中获取。

<Simulator>
    <Flight ID="1" Description="rainy_day">
      <Instructor Num="14213124">
        <Name>Jack</Name>
        <Surname>Sparrow</Surname>
        <Rank>General</Rank>
      </Instructor>
      <Student Num="56475679">
        <Name>Adam</Name>
        <Surname>Black</Surname>
        <Rank>Lieutenant</Rank>
      </Student>
      <Operator Num="75846474">
        <Name>Gabriel</Name>
        <Surname>Red</Surname>
        <Rank>Op</Rank>
      </Operator>
      <Technician Num="85425484">
        <Name>Samuel</Name>
        <Surname>Long</Surname>
        <Rank>Tec</Rank>
      </Technician>
    </Flight>
</Simulator>

这是我试过的代码。如果我一遍又一遍地为每个员工写这个代码,它会很长

XmlDeclaration xmlDeclaration = xmlDoc.CreateXmlDeclaration("1.0", "UTF-8", "yes");
                XmlElement rootNode = xmlDoc.DocumentElement;
                xmlDoc.InsertAfter(xmlDeclaration, rootNode);

                XmlNode parentNode = xmlDoc.CreateElement("Users");
                XmlNode subNode = xmlDoc.CreateElement("Instructor");

                XmlAttribute numAtt = xmlDoc.CreateAttribute("Num");
                numAtt.Value = num.ToString();
                XmlAttribute nameAtt = xmlDoc.CreateAttribute("Name");
                nameAtt.Value = name;
                XmlAttribute surnameAtt = xmlDoc.CreateAttribute("Surname");
                surnameAtt.Value = surname;
                XmlAttribute rankAtt = xmlDoc.CreateAttribute("Rank");
                rankAtt.Value = rank;

                subNode.Attributes.Append(numAtt);
                subNode.Attributes.Append(nameAtt);
                subNode.Attributes.Append(surnameAtt);
                subNode.Attributes.Append(rankAtt);

                xmlDoc.AppendChild(parentNode);
                parentNode.AppendChild(subNode);

检查ID部件

var userElements = xDoc.Descendants("Flight").ToList();
            string lastID = userElements.Select(x => (x.Attribute("ID").Value))
                  .OrderByDescending(x => x)
                  .First()
                  .ToString();
            int lastID_int = Int16.Parse(lastID) + 1;
            if (lastID_int <= 0)
                lastID_int = 0;
            string current = lastID_int.ToString();
            Simulator sim = new Simulator(current, textbox_description.Text);
6gpjuf90

6gpjuf901#

下面是使用XML Linq的类:

public class Simulator
    {
        XDocument doc = null;
        public Simulator(string filename)
        {
            doc = XDocument.Load(filename);
        }
        public Simulator(string id, string description)
        {
            string ident = "<?xml version=\"1.0\" encoding=\"utf-8\"?><Simulator></Simulator>";
            doc = XDocument.Parse(ident);
            XElement flight = new XElement("Flight", new object[] {
                new XAttribute("ID", id),
                new XAttribute("Description", description)
            });

            doc.Root.Add(flight);
        }
        public string AddUser(string flightID, string role, string number, string name, string surname, string rank)
        {
            XElement flight = doc.Descendants("Flight").Where(x => (string)x.Attribute("ID") == flightID).FirstOrDefault();

            if (flight != null)
            {
                XElement user = new XElement(role, new object[] {
                    new XAttribute("Num", number),
                    new XElement("Name", name),
                    new XElement ("Surname", surname),
                    new XElement("Rank", rank)
                });
                flight.Add(user);
                return "GOOD";
            }
            else
            {
                return "Flight ID doesn't exist";
            }
        }
        public string AddFlight(string flightID, string description)
        {
            XElement flight = doc.Descendants("Flight").Where(x => (string)x.Attribute("ID") == flightID).FirstOrDefault();
            if (flight == null)
            {
                flight = new XElement("Flight", new object[] {
                    new XAttribute("ID", flightID),
                    new XAttribute("Description", description)
                });
                doc.Root.Add(flight);
                return "Good";
            }
            else
            {
                return "Flight ID already exists";
            }
        }
        public string AddErrors(string flightID, XElement errorLog)
        {
            XElement flight = doc.Descendants("Flight").Where(x => (string)x.Attribute("ID") == flightID).FirstOrDefault();
            if(flight == null)
            {
                return "Flight ID doesn't exist";
            }
            else
            {
                flight.Add(errorLog);
                return "GOOD";
            }

        }

        public void WriteXml(string filename)
        {
            doc.Save(filename);
        }
    }
vs91vp4v

vs91vp4v2#

您可能应该使用xmlSerializer,而不是尝试手动创建xml树。
这应该可以让您为数据创建类,并让序列化程序负责将对象转换为xml:

public class Person{
    public string Num{get;set;}
    public string Name {get;set;}
    public string Surname {get;set;}
    public string Rank{get;set;}
}
public class Flight{
    public Person Instructor {get;set;}
    public Person Student {get;set;}
    ....
}

var serializer = new XmlSerializer(typeof(Flight));
var writer = new StreamWriter(filename);
serializer.Serialize(writer, myFlight);

这可能不会给予您想要的确切布局,但通常可以是controlled by attributes

相关问题