Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/306.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 更优雅/高效的方法?(XML/Linq/Read&;Write)_C#_.net_Xml_Winforms_Linq - Fatal编程技术网

C# 更优雅/高效的方法?(XML/Linq/Read&;Write)

C# 更优雅/高效的方法?(XML/Linq/Read&;Write),c#,.net,xml,winforms,linq,C#,.net,Xml,Winforms,Linq,所以我的代码是正确的,它基本上读取一个XML文件,并执行一些if's来检查一些事情,然后在画布(面板)上放置适当的控件 但是它很长。或者,比我希望的要长。这个代码就像。。。现在两三岁了 我想做的是使用Linq转换为XML 正在读取XML文件: OpenFileDialog o = new OpenFileDialog(); o.Filter = "wordreplaced Multimedia Format (*.mf)|*.mf|" +

所以我的代码是正确的,它基本上读取一个XML文件,并执行一些if's来检查一些事情,然后在画布(面板)上放置适当的控件

但是它很长。或者,比我希望的要长。这个代码就像。。。现在两三岁了

我想做的是使用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;
                }
            }
            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文件:

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;
                }
            }
            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;
                    }
                }
            }
这很好用。一点问题都没有。但是,尝试扩展/使用etc实在是一团糟。我需要一种更高效/更干净/优雅的方式来写入和读取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行,而不是几十行。将事物分解成小的、可重用的、最重要的是可读的块,用清晰的名称声明它们的意图,因此,你的代码读起来更像是你的思维过程,而不像是一长串神奇的咒语,它们以某种方式让计算机做你想让它做的事情。

我认为你的问题不在于使用错误的类或工具,而在于你需要学习如何提取方法并停止以那种方式重复代码

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

// 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行,而不是几十行。将事情分解成小的、可重复使用的、最重要的是可读的块,用清晰的名称声明它们的意图,这样你的代码读起来更像是你的思维过程,而不像是一长串神奇的咒语,以某种方式让计算机做你想让它做的事情。

代码有效吗?您是否有任何新的要求需要实施?你没有更重要的事要做吗


如果它没有坏,就不要修理它。您只会引入bug。

代码有效吗?您是否有任何新的要求需要实施?你没有更重要的事要做吗


如果它没有坏,就不要修理它。您只是要引入bug。

您不是已经在使用LINQ到XML了吗?XDocument位于System.Xml中。林克集会。是的,但它和我见过的其他地方真的不一样。它太笨重/难看/长了,这完全是另一回事。你想要的是重构你的代码,而不是使用不同的技术;不要拿更大的锤子,改变你使用它的方式。你不是已经在使用LINQtoXML了吗?XDocument位于System.Xml中。林克集会。是的,但它和我见过的其他地方真的不一样。它太笨重/难看/长了,这完全是另一回事。你想要的是重构你的代码,而不是使用不同的技术;不要拿更大的锤子,改变你使用它的方式。“一长串神奇的咒语,以某种方式让电脑做你想让它做的事。”-哈哈。谢谢你的帮助和建议,@Domenic。非常感谢。:)“一长串神奇的咒语,不知何故让电脑做你想让它做的事。”-哈哈。谢谢你的帮助和建议,@Domenic。非常感谢。:)“如果它没坏,就别修了。”-我同意。但我只是觉得这是,我不知道。我只是认为应该/有一个更好的方法来替代XML/Linq。不,我真的没有更好的事情要做,是的,我需要添加更多的属性,比如地图和时区信息。但我已经可以做到了。我只是希望有更好的方法来做我已经在做的事情。毫无疑问,有,嘿,我支持学习新的方法来做事情和改进。但请注意,您很可能会引入bug。@柯克·布罗德赫斯特:除非您编写单元测试以便能够毫无恐惧地编写代码@Domenic是个不错的主意,但您不能对所有可能的场景进行单元测试。如果这是我的代码,我也想对其进行重构,但我知道,除非这样做能带来明显的业务好处,否则这是没有意义的&不应该这样做。每隔几周更新一次代码,然后是的,它需要检查。每隔几年更新一次代码?柯克:我相信很多人(我指的是我们应该学习的行业巨头)会不同意你的第一句话。更重要的是,在这种情况下,您可以对原始代码打算处理的每个场景进行单元测试。“如果没有损坏,就不要修复它。”-我同意。但我只是觉得这是,我不知道。我只是认为应该/有一个更好的方法来替代XML/Linq。不,我真的没有更好的事情要做,是的,我需要添加更多的属性,比如地图和时区信息。但我已经可以做到了。我只是希望有更好的方法来做我已经在做的事情。毫无疑问,有,嘿,我支持学习新的方法来做事情和改进。但请注意,您很可能会引入bug。@柯克·布罗德赫斯特:除非您编写单元测试以便能够毫无恐惧地编写代码@Domenic是个不错的主意,但您不能对所有可能的场景进行单元测试。如果这是我的代码,我