【问题标题】:XML Serialize writing everything to one file onlyXML序列化只将所有内容写入一个文件
【发布时间】:2016-02-25 04:59:17
【问题描述】:

关于这个问题: Create a XML File from a list based on a conditional 我解决了我遇到的问题,并看到了 Xml.Serialization 的简单用法。

现在运行程序会写入我期望的 XML - 但它会在所有文件中写入所有数据。 IE: file1 应该有 颜色 = #FF9032 颜色名称 = WhoKnows 文件 2 应该有 颜色 = #FE9034 颜色名称 = 有人知道

当程序运行时,他也将文件 2 中的信息写入文件 1。基本上,如果我有 8 个文件要处理,他会将这 8 个文件中的所有信息(颜色和颜色名称)写在 8 个文件上。

这种行为是从哪里来的,我该如何解决?

非常感谢任何帮助。谢谢。

XML 编写代码(其他可以在上一题中找到)。

public void writexml(xmldatalist XMLList, variables GlobalVars)
{
    XmlWriterSettings settings = new XmlWriterSettings
    {
        Indent = true,
        IndentChars = "\t",
        NewLineChars = Environment.NewLine,
        NewLineHandling = NewLineHandling.Replace,
        Encoding = new UTF8Encoding(false)
    };

    foreach(var item in XMLList.FullList)
    {
        if (!XMLList.xmlFiles.ContainsKey(item.xml_filename))
        {
            XMLList.xmlFiles[item.xml_filename] = new List<xmldata>();
            XMLList.xmlFiles[item.xml_filename].Add(item);
        }

    }
    string DesktopFolder = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
    string XmlFilename = GlobalVars.CompleteFileName;
    XmlFilename = GlobalVars.CompleteFileName;

    string FileExtension = ".xml";
    string PathString = Path.Combine(DesktopFolder, "XML");
    System.IO.Directory.CreateDirectory(PathString);
    string FullPath = Path.Combine(PathString, XmlFilename + FileExtension);
    foreach (var i in XMLList.xmlFiles)
    {
        string Xname = i.Key;
        string XMLName = Path.Combine(PathString, Xname + FileExtension);
        List<xmldata> xmlDataOfThisFile = i.Value;
        Console.WriteLine(Xname);
        try
        {
            using (XmlWriter XmlWriting = XmlWriter.Create(XMLName, settings))
            {
                XmlWriting.WriteStartDocument();
                XmlWriting.WriteStartElement("JMF");
                XmlWriting.WriteAttributeString("SenderID", "InkZone-Controller");
                XmlWriting.WriteAttributeString("Version", "1.2");
                //XmlWriting.WriteAttributeString("xmlns","",null, "http://www.CIP4.org/JDFSchema_1_1");

                XmlWriting.WriteStartElement("Command");
                XmlWriting.WriteAttributeString("ID", "cmd.00695");
                XmlWriting.WriteAttributeString("Type", "Resource");


                XmlWriting.WriteStartElement("ResourceCMDParams");
                XmlWriting.WriteAttributeString("ResourceName", "InkZoneProfile");
                XmlWriting.WriteAttributeString("JobID", "K_41");


                XmlWriting.WriteStartElement("InkZoneProfile");
                XmlWriting.WriteAttributeString("ID", "r0013");
                XmlWriting.WriteAttributeString("Class", "Parameter");
                XmlWriting.WriteAttributeString("Locked", "false");
                XmlWriting.WriteAttributeString("Status", "Available");
                XmlWriting.WriteAttributeString("PartIDKeys", "SignatureName SheetName Side Separation");
                XmlWriting.WriteAttributeString("DescriptiveName", "Schieberwerte von DI");
                XmlWriting.WriteAttributeString("ZoneWidth", "32");


                XmlWriting.WriteStartElement("InkZoneProfile");
                XmlWriting.WriteAttributeString("SignatureName", "SIG1");

                XmlWriting.WriteStartElement("InkZoneProfile");
                XmlWriting.WriteAttributeString("Locked", "False");
                XmlWriting.WriteAttributeString("SheetName", "S1");

                XmlWriting.WriteStartElement("InkZoneProfile");
                XmlWriting.WriteAttributeString("Side", "Front");
                XmlSerializer serializer = new XmlSerializer(typeof(List<xmldata>));
                serializer.Serialize(XmlWriting, XMLList.FullList);
                XmlWriting.WriteEndElement();
                XmlWriting.WriteEndDocument();
                XmlWriting.Close();
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
            Console.WriteLine(ex.InnerException);
        }
    }
}

编辑:添加代码 - 类现在的所有内容

EDIT2:由于属性是固定的,我在类上定义了它们。

   namespace PPF_Converter_v6
{
    [XmlRoot("JMF",Namespace = "http://www.CIP4.org/JDFSchema_1_1")]
    public class JMF
    {

        [XmlElement("SenderID")]
        public string SenderID { get; set; }

        [XmlElement("Version")]
        public string Version { get; set; }

        public JMF()
        {
            SenderID = "InkZone-Controller";
            Version = "1.2";
        }

    }
    [XmlType("InkZoneProfile")]
    public class xmldata //Class to receive items list
    {
        [XmlIgnore]
        public string xml_filename { get; set; }

        [XmlAttribute("Separation")]
        public string colorname { get; set; }

        [XmlAttribute("ZoneSettingsX")]
        public string colorvalues { get; set; }

    }
    [Serializable]
    public class Command
    {
        [XmlAttribute("ID")]
        public string ID { get; set; }

        [XmlAttribute("Type")]
        public string Type { get; set; }

        public Command()
        {
            ID = "cmd.00695";
            Type = "Resource";
        }
        public ResourceCmdParams ResourceCmdParams { get; set; }
    }
    [Serializable]
    public class ResourceCmdParams
    {
        [XmlAttribute("ResourceName")]
        public string ResourceName { get; set; }

        [XmlAttribute("JobID")]
        public string JobID { get; set; }

        public ResourceCmdParams()
        {
            ResourceName = "InkZoneProfile";
            JobID = "K_41";
        }

        public InkZoneProfile InkZoneProfile { get; set; }
    }

    [Serializable]
    public class InkZoneProfile
    {
        [XmlAttribute("ID")]
        public string ID { get; set; }

        [XmlAttribute("Class")]
        public string Class { get; set; }

        [XmlAttribute("Locked")]
        public string Locked { get; set; }

        [XmlAttribute("Status")]
        public string Status { get; set; }

        [XmlAttribute("PartIDKeys")]
        public string PartIDKeys { get; set; }

        [XmlAttribute("DescriptiveName")]
        public string DescriptiveName { get; set; }

        [XmlAttribute("ZoneWidth")]
        public string ZoneWidth { get; set; }

        public InkZoneProfile()
        {
            ID = "r0013";
            Class = "Parameter";
            Locked = "False";
            Status = "Available";
            PartIDKeys = "SignatureName SheetName Side Separation";
            DescriptiveName = "Schieberwerte von DI";
            ZoneWidth = "32";
        }

        public InkZoneProfile2 InkZoneProfile2 { get; set; }
    }
    public class InkZoneProfile2 //Since InkZoneProfile was in use for class name, i just incremented it. Default name still is InkZoneProfile
    {
        [XmlAttribute("SignatureName")]
        public string SignatureName { get; set; }

        public InkZoneProfile2()
        {
            SignatureName = "SIG1";
        }

        public InkZoneProfile3 InkZoneProfile3 { get; set; }

    }
    public class InkZoneProfile3
    {
        [XmlAttribute("Locked")]
        public string Locked { get; set; }

        [XmlAttribute("SheetName")]
        public string SheetName { get; set; }

        public InkZoneProfile3()
        {
            Locked = "False";
            SheetName = "S1";
        }
    }
    public class xmldatalist
    {
        public List<xmldata> FullList = new List<xmldata>();
        public Dictionary<string, List<xmldata>> xmlFiles = new Dictionary<string, List<xmldata>>();
    }
    public class variables //All variables goes here - only smaller stuff goes into the code
    {

        public string aux { get; set; }
        public string colors { get; set; }
        public string[] colors_str { get; set; }
        public int nfiles { get; set; }
        public string definedpath { get; set; }
        public string contents { get; set; }
        public string values { get; set; }
        public string CompleteFileName { get; set; }
        public string[] FilesNames { get; set; }

    }
    class Program
    {
        public void writexml(xmldatalist XMLList, variables GlobalVars)
        {
            XmlWriterSettings settings = new XmlWriterSettings
            {
                Indent = true,
                IndentChars = "\t",
                NewLineChars = Environment.NewLine,
                NewLineHandling = NewLineHandling.Replace,
                Encoding = new UTF8Encoding(false)
            };

            foreach (var item in XMLList.FullList)
            {
                if (!XMLList.xmlFiles.ContainsKey(item.xml_filename))
                {
                    XMLList.xmlFiles[item.xml_filename] = new List<xmldata>();
                    XMLList.xmlFiles[item.xml_filename].Add(item);
                }

            }
            string DesktopFolder = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
            string XmlFilename = GlobalVars.CompleteFileName;
            XmlFilename = GlobalVars.CompleteFileName;

            string FileExtension = ".xml";
            string PathString = Path.Combine(DesktopFolder, "XML");
            System.IO.Directory.CreateDirectory(PathString);
            string FullPath = Path.Combine(PathString, XmlFilename + FileExtension);
            foreach (var i in XMLList.xmlFiles)
            {
                string Xname = i.Key;
                string XMLName = Path.Combine(PathString, Xname + FileExtension);
                List<xmldata> xmlDataOfThisFile = i.Value;
                Console.WriteLine(Xname);
                try
                {
                    using (XmlWriter XmlWriting = XmlWriter.Create(XMLName, settings))
                    {
                        XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
                        ns.Add("myNamespace", "http://www.CIP4.org/JDFSchema_1_1");
                        XmlSerializer serializer = new XmlSerializer(typeof(List<xmldata>));
                        serializer.Serialize(Console.Out, xmlDataOfThisFile);
                        XmlWriting.WriteEndElement();
                        XmlWriting.WriteEndDocument();
                        XmlWriting.Close();
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    Console.WriteLine(ex.InnerException);
                }
            }
        }

【问题讨论】:

  • 我建议您将任何XmlWriting.WriteAttributeStringXmlWriting.WriteStartElement 更改为xmldata 类之类的类。这样您就可以更轻松地控制和管理您的代码。
  • 调用JMF jmf = new JMF(); 将数据添加到jmf 看看它是否有效。如果没有,请在此处发布您的代码,我会为您提供帮助。
  • 我编辑了代码。根据我阅读的一篇文章,我已经定义了属性。
  • 尝试将其序列化到文件中,看看它是否有效。如果不是,请发布您的代码,我可以为您修复。
  • 我将输出更改为控制台,以便更好地调试。到目前为止,唯一添加的属性是 InkZoneProfile 。我也试图摆脱“ArrayOf”(阅读)。我当前的代码是 EDIT2 上的代码。

标签: c# xml xmlserializer


【解决方案1】:

变化:

serializer.Serialize(XmlWriting, XMLList.FullList);

收件人:

serializer.Serialize(XmlWriting, xmlDataOfThisFile);

MSDN 不错,也可以在 stackoverflow.com 和 codeproject.com 上搜索

如果您可以将上面的代码转换为类,我会亲自帮助您。

您需要将这些东西转换为类:JMFCommandResourceCmdParams,...

例子:

[Serializable]
public class JMF
{
    [XmlAttribute("SenderID")]
    public string SenderID { get; set; }

    [XmlAttribute("Version")]
    public string Version { get; set; }

    public Command Command { get; set; }
}

[Serializable]
public class Command
{
    [XmlAttribute("ID")]
    public string ID{get;set;}

    [XmlAttribute("Type")]
    public string Type { get; set; }

    public ResourceCmdParams {get; set;}
}

【讨论】:

  • 通过这样做,他添加了每个文件的第一个属性并移动到下一个。我试图弄清楚序列化是如何工作的——你推荐任何其他文档而不是 MSDN?
  • 我明白你为什么告诉我将所有内容都更改为类 - 因为我正在序列化数据,所以更容易控制数据输入\输出。我改变了你告诉我的方式,但我完全不知道我将如何继续编写 XML。我一直在检查 MSDN、StackOverflow 和 C# Corner - 这就是我到达这一点的原因:)
  • 没关系。你做了我在这里测试过的事情(序列化 JMF)。感谢从现在开始我可以处理的一切\做一些事情\弄清楚。非常感谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-12
  • 1970-01-01
  • 2016-07-30
  • 1970-01-01
相关资源
最近更新 更多