繁体   English   中英

更优雅/有效的方法呢? (XML / Linq /读写)

[英]More elegant/efficient way of doing this? (XML/Linq/Read & Write)

因此,我拥有正确的代码,它基本上读取XML文件,并执行一些if检查某些事情,然后将适当的Controls放到Canvas(面板)上。

但这很长。 或者,比我想要的更长。 这个代码就像...现在2或3年了。

我想做的是使用Linq到XML。

从XML文件读取:

OpenFileDialog o = new OpenFileDialog();

            o.Filter =
                "wordreplaced Multimedia Format (*.mf)|*.mf|" +
                "Word Document (*.docx)|*.docx|" +
                "PDF Document (*.pdf)|*.pdf|" +
                "Text FIle (*.txt)|*.txt";
            o.Title = "wordreplaced 11 - Open Document";

            using (o)
            {
                if (o.ShowDialog() == DialogResult.OK)
                {
                    foreach (var controlTag in XDocument.Load(o.FileName).Root.Elements())
                    {
                        var controlType = Type.GetType(
                            string.Format(
                            "System.Windows.Forms.{0}, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089",
                            controlTag.Name.LocalName), false);
                        if (controlType == null || !typeof(Control).IsAssignableFrom(controlType))
                        {
                            continue;
                        }

                        var control = (Control)Activator.CreateInstance(controlType);
                        control.Text = controlTag.Attributes("Content").First().Value;

                        try
                        {
                            control.ForeColor = Color.FromArgb(
                                int.Parse(controlTag.Attributes("A").First().Value),
                                int.Parse(controlTag.Attributes("R").First().Value),
                                int.Parse(controlTag.Attributes("G").First().Value),
                                int.Parse(controlTag.Attributes("B").First().Value));

                            Font font = FromString(controlTag.Attributes("Font").First().Value);
                            control.Font = font;
                        }
                        catch { continue; }

                        control.BackColor = Color.Transparent;

                        control.MouseDown += new MouseEventHandler(control_MouseDown);
                        control.MouseMove += new MouseEventHandler(control_MouseMove);
                        control.MouseUp += new MouseEventHandler(control_MouseUp);
                        control.MouseClick += new MouseEventHandler(control_MouseClick);
                        control.MouseDoubleClick += new MouseEventHandler(control_MouseDoubleClick);

                        string boldness = Convert.ToString(controlTag.Attributes("Bold"));

                        if (boldness == "yeah")
                            control.Font = new Font(control.Font.Name, control.Font.Size, FontStyle.Bold);
                        Type t = control.GetType();
                        if (t.Name == "Label")
                        {
                            Label label = (Label)control;
                            label.AutoSize = true;
                            label.Location = new Point(
                                Convert.ToInt32(controlTag.Attributes("LocationX").First().Value),
                                Convert.ToInt32(controlTag.Attributes("LocationY").First().Value));


                            Canvas.Controls.Add(label);

                            // handlers.
                            label.MouseDown += new MouseEventHandler(label_MouseDown);
                            label.MouseMove += new MouseEventHandler(label_MouseMove);
                            label.MouseUp += new MouseEventHandler(label_MouseUp);
                            label.MouseClick += new MouseEventHandler(label_MouseClick);
                            label.MouseDoubleClick += new MouseEventHandler(label_MouseDoubleClick);
                        }
                        else if (t.Name == "LinkLabel")
                        {
                            control.Tag = controlTag.Attributes("Address").First().Value;
                            LinkLabel link = (LinkLabel)control;
                            link.AutoSize = true;
                            link.Location = new Point(
                                Convert.ToInt32(controlTag.Attributes("LocationX").First().Value),
                                Convert.ToInt32(controlTag.Attributes("LocationY").First().Value));

                            if (boldness == "yeah")
                                control.Font = new Font(control.Font.Name, control.Font.Size, FontStyle.Bold);

                            link.LinkColor = Color.White;

                            Canvas.Controls.Add(link);

                            // Add handlers.
                            link.MouseDown += new MouseEventHandler(link_MouseDown);
                            link.MouseMove += new MouseEventHandler(link_MouseMove);
                            link.MouseUp += new MouseEventHandler(link_MouseUp);
                            link.MouseClick += new MouseEventHandler(link_MouseClick);
                            link.MouseDoubleClick += new MouseEventHandler(link_MouseDoubleClick);
                        }
                        else if (t.Name == "PictureBox")
                        {
                            PictureBox p = (PictureBox)control;
                            p.Image = Base64ToImage(controlTag.Attributes("Content").First().Value);
                            p.AutoSize = true;
                            p.Location = new Point(
                                Convert.ToInt32(controlTag.Attributes("LocationX").First().Value),
                                Convert.ToInt32(controlTag.Attributes("LocationY").First().Value));

                            Canvas.Controls.Add(p);

                            // Add handlers.
                            p.MouseDown += new MouseEventHandler(p_MouseDown);
                            p.MouseMove += new MouseEventHandler(p_MouseMove);
                            p.MouseUp += new MouseEventHandler(p_MouseUp);
                            p.MouseClick += new MouseEventHandler(p_MouseClick);
                            p.MouseDoubleClick += new MouseEventHandler(p_MouseDoubleClick);
                        }
                    }
                    this.Text = "wordreplaced 11 - " + o.FileName;
                }
            }

写入XML文件:

            SaveFileDialog s = new SaveFileDialog();

            s.Filter =
                "wordReplaced Multimedia Format (*.mf)|*.mf|" +
                "Word Document (*.docx)|*.docx|" +
                "PDF Document (*.pdf)|*.pdf|" +
                "Text FIle (*.txt)|*.txt";
            s.Title = "wordReplaced 11 - Save Document";
            s.CheckFileExists =
                false;
            XElement d;

            using (s)
            {
                if (s.ShowDialog() == DialogResult.OK)
                {
                    if (File.Exists(s.FileName))
                        d = XElement.Load(s.FileName);
                    else
                        d = new XElement("cs");

                    foreach (Control control in Canvas.Controls)
                    {
                        Type t = control.GetType();

                        switch (t.Name)
                        {
                            case "JTS.TextBox":
                                XElement xe0 = new XElement("JTS.TextBox",
                                    new XAttribute("Content", control.Text),
                                    new XAttribute("LocationX", control.Location.X),
                                    new XAttribute("LocationY", control.Location.Y),
                                    new XAttribute("A", control.ForeColor.A),
                                    new XAttribute("R", control.ForeColor.R),
                                    new XAttribute("G", control.ForeColor.G),
                                    new XAttribute("B", control.ForeColor.B),
                                    new XAttribute("Font", control.Font),
                                    new XAttribute("Bold", "yeah"));
                                d.Add(xe0);
                                break;
                            case "LinkLabel":
                                LinkLabel ll = (LinkLabel)control;

                                try
                                {
                                    XElement xe1 = new XElement("LinkLabel",
                                        new XAttribute("Content", control.Text),
                                        new XAttribute("LocationX", control.Location.X),
                                        new XAttribute("LocationY", control.Location.Y),
                                        new XAttribute("A", ll.LinkColor.A),
                                        new XAttribute("R", ll.LinkColor.R),
                                        new XAttribute("G", ll.LinkColor.G),
                                        new XAttribute("B", ll.LinkColor.B),
                                        new XAttribute("Font", ll.Font),
                                        new XAttribute("Address", control.Tag),
                                        new XAttribute("Bold", "yeah"));
                                    d.Add(xe1);
                                }
                                catch
                                {
                                    XElement xe1 = new XElement("LinkLabel",
                                        new XAttribute("Content", control.Text),
                                        new XAttribute("LocationX", control.Location.X),
                                        new XAttribute("LocationY", control.Location.Y),
                                        new XAttribute("A", ll.LinkColor.A),
                                        new XAttribute("R", ll.LinkColor.R),
                                        new XAttribute("G", ll.LinkColor.G),
                                        new XAttribute("B", ll.LinkColor.B),
                                        new XAttribute("Font", ll.Font),
                                        new XAttribute("Bold", "yeah"));
                                    d.Add(xe1);
                                }

                                break;
                            case "PictureBox":
                                PictureBox px = (PictureBox)control;
                                string ie = ImageToBase64(px.InitialImage, System.Drawing.Imaging.ImageFormat.Bmp);

                                XElement xe2 = new XElement("PictureBox",
                                    new XAttribute("Content", ie),
                                    new XAttribute("LocationX", px.Location.X),
                                    new XAttribute("LocationY", px.Location.Y));
                                d.Add(xe2);
                                break;
                            default:
                                break;
                        }
                        d.Save(s.FileName);

                        FilePath = s.FileName;
                        Text = s.FileName;

                        ds = true;
                    }
                }
            }

哪个工作正常。 还没有一个单一的问题。 但是,尝试扩展/使用等只是一团糟。我需要一种更有效/更干净/优雅的方式来写入和读取XML文件,并对它们执行linq查询。

我读了一些教程和一篇文章,但是我不太明白。 一个网站提到了StreamWriter,它没有任何意义,而且似乎有很多不同的方法可以使用Linq读写XML文件,这一切都让我感到困惑。

非常感谢您的帮助,

谢谢

我认为您的问题不仅仅在于使用错误的类或工具,还在于您需要更多的知识来学习如何提取方法并停止以这种方式重复代码。

理想情况下,第一个代码应为:

// In whatever method loads the file
string fileName = GetFileNameFromUser();
if (fileName != null)
{
    var rootElement = GetRootElementOfXmlFile(fileName);
    foreach (var controlTag in rootElement)
    {
        ProcessControlTag(controlTag);
    }
}

private static void ProcessControlTag(XElement controlTag)
{
    var type = GetControlType(controlTag);
    if (type == null)
    {
        return;
    }

    var control = CreateControl(controlType, controlTag);
    Canvas.Controls.Add(control);
}

private static void CreateControl(Type controlType, XElement controlTag)
{
    var control = (Control)Activator.CreateInstance(controlType);
    AddCommonControlModifications(control, controlTag);

    if (controlType.Name == "Label")
    {
        AddLabelModifications(control, controlTag);
    }
    else if (controlType.Name == "LinkLabel")
    {
        AddLinkLabelModifications(control, controlTag);
    }
    else if (controlType.Name == "PictureBox")
    {
        AddPictureBoxModifications(control, controlTag);
    }
}

只是为了让您入门; 我没有实现其中的几种方法。 每当您重复执行代码(例如,位置设置代码或使您在try / catch内两次重复执行代码的操作)时,都可以将其提取到方法中。

方法通常应为3--5行长,而不是数十行。 将事情分解成小的,可重用的,最重要的是可读的块,用清晰的名称声明其意图,从而使您的代码读起来更像是您的思维过程,而不是像一系列神奇的咒语那样,它们使计算机按照您想要的方式工作去做。

代码有效吗? 您是否有任何新要求要实施? 您没有其他重要的事情了吗?

如果没有损坏,请不要修复。 您将要介绍错误。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM