Заполнение XML по XSD - C#

Узнай цену своей работы

Формулировка задачи:

Доброго времени суток, уважаемые! Вопрос по заполнению XML файла по известной схеме XSD. Что имеем: 1) схема XSD
<?xml version="1.0" encoding="windows-1251"?>
<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="REF">
    <xs:complexType>
      <xs:sequence>
        <xs:element maxOccurs="unbounded" name="MAIN">
          <xs:complexType>
            <xs:sequence>
              <xs:element name="MAIN_LINE">
                <xs:complexType>
                  <xs:sequence>
                    <xs:element name="MAIN_LINE" maxOccurs="1">
                      <xs:complexType>
                        <xs:attribute name="DATE" type="xs:date" use="required" />
                        <xs:attribute name="COMMENT" type="xs:string" use="required" />
                      </xs:complexType>
                    </xs:element>
                  </xs:sequence>
                </xs:complexType>
              </xs:element>
            </xs:sequence>
            <xs:attribute name="ID" type="xs:unsignedInt" use="required" />
          </xs:complexType>
        </xs:element>
      </xs:sequence>
      <xs:attribute name="name" type="xs:string" use="required" />
      <xs:attribute name="action" type="xs:string" use="required" />
    </xs:complexType>
  </xs:element>
</xs:schema>
2) сгенерированный класс по схеме (использовал http://www.httputility.net/xsd-to-csharp-vb-class.aspx и утилиту Xsd2Code)
using System;
using System.Diagnostics;
using System.Xml.Serialization;
using System.Collections;
using System.Xml.Schema;
using System.ComponentModel;
using System.IO;
using System.Text;

namespace AutoGeneratedCode
{
   
   /// <remarks/>
   [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Xml", "4.0.30319.34234")]
   [System.SerializableAttribute()]
   [System.Diagnostics.DebuggerStepThroughAttribute()]
   [System.ComponentModel.DesignerCategoryAttribute("code")]
   [System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
   [System.Xml.Serialization.XmlRootAttribute(Namespace="", IsNullable=false)]
   public partial class REF
   {
      private REFMAIN[] mAINField;
      private string nameField;
      private string actionField;
 
      private static System.Xml.Serialization.XmlSerializer serializer;
 
      /// <remarks/>
      [System.Xml.Serialization.XmlElementAttribute("MAIN")]
      public REFMAIN[] MAIN
      {
         get
         {
            return this.mAINField;
         }
         set
         {
            this.mAINField = value;
         }
      }
      /// <remarks/>
      [System.Xml.Serialization.XmlAttributeAttribute()]
      public string name
      {
         get
         {
            return this.nameField;
         }
         set
         {
            this.nameField = value;
         }
      }
      /// <remarks/>
      [System.Xml.Serialization.XmlAttributeAttribute()]
      public string action
      {
         get
         {
            return this.actionField;
         }
         set
         {
            this.actionField = value;
         }
      }
 
        private static System.Xml.Serialization.XmlSerializer Serializer {
            get {
                if ((serializer == null)) {
                    serializer = new System.Xml.Serialization.XmlSerializer(typeof(REF));
                }
                return serializer;
            }
        }
        
        #region Serialize/Deserialize
        /// <summary>
        /// Serializes current REF object into an XML document
        /// </summary>
        /// <returns>string XML value</returns>
        public virtual string Serialize() {
            System.IO.StreamReader streamReader = null;
            System.IO.MemoryStream memoryStream = null;
            try {
                memoryStream = new System.IO.MemoryStream();
                Serializer.Serialize(memoryStream, this);
                memoryStream.Seek(0, System.IO.SeekOrigin.Begin);
                streamReader = new System.IO.StreamReader(memoryStream);
                return streamReader.ReadToEnd();
            }
            finally {
                if ((streamReader != null)) {
                    streamReader.Dispose();
                }
                if ((memoryStream != null)) {
                    memoryStream.Dispose();
                }
            }
        }
        
        /// <summary>
        /// Deserializes workflow markup into an REF object
        /// </summary>
        /// <param name="xml">string workflow markup to deserialize</param>
        /// <param name="obj">Output REF object</param>
        /// <param name="exception">output Exception value if deserialize failed</param>
        /// <returns>true if this XmlSerializer can deserialize the object; otherwise, false</returns>
        public static bool Deserialize(string xml, out REF obj, out System.Exception exception) {
            exception = null;
            obj = default(REF);
            try {
                obj = Deserialize(xml);
                return true;
            }
            catch (System.Exception ex) {
                exception = ex;
                return false;
            }
        }
        
        public static bool Deserialize(string xml, out REF obj) {
            System.Exception exception = null;
            return Deserialize(xml, out obj, out exception);
        }
        
        public static REF Deserialize(string xml) {
            System.IO.StringReader stringReader = null;
            try {
                stringReader = new System.IO.StringReader(xml);
                return ((REF)(Serializer.Deserialize(System.Xml.XmlReader.Create(stringReader))));
            }
            finally {
                if ((stringReader != null)) {
                    stringReader.Dispose();
                }
            }
        }
        
        /// <summary>
        /// Serializes current REF object into file
        /// </summary>
        /// <param name="fileName">full path of outupt xml file</param>
        /// <param name="exception">output Exception value if failed</param>
        /// <returns>true if can serialize and save into file; otherwise, false</returns>
        public virtual bool SaveToFile(string fileName, out System.Exception exception) {
            exception = null;
            try {
                SaveToFile(fileName);
                return true;
            }
            catch (System.Exception e) {
                exception = e;
                return false;
            }
        }
        
        public virtual void SaveToFile(string fileName) {
            System.IO.StreamWriter streamWriter = null;
            try {
                string xmlString = Serialize();
                System.IO.FileInfo xmlFile = new System.IO.FileInfo(fileName);
                streamWriter = xmlFile.CreateText();
                streamWriter.WriteLine(xmlString);
                streamWriter.Close();
            }
            finally {
                if ((streamWriter != null)) {
                    streamWriter.Dispose();
                }
            }
        }
        
        /// <summary>
        /// Deserializes xml markup from file into an REF object
        /// </summary>
        /// <param name="fileName">string xml file to load and deserialize</param>
        /// <param name="obj">Output REF object</param>
        /// <param name="exception">output Exception value if deserialize failed</param>
        /// <returns>true if this XmlSerializer can deserialize the object; otherwise, false</returns>
        public static bool LoadFromFile(string fileName, out REF obj, out System.Exception exception) {
            exception = null;
            obj = default(REF);
            try {
                obj = LoadFromFile(fileName);
                return true;
            }
            catch (System.Exception ex) {
                exception = ex;
                return false;
            }
        }
        
        public static bool LoadFromFile(string fileName, out REF obj) {
            System.Exception exception = null;
            return LoadFromFile(fileName, out obj, out exception);
        }
        
        public static REF LoadFromFile(string fileName) {
            System.IO.FileStream file = null;
            System.IO.StreamReader sr = null;
            try {
                file = new System.IO.FileStream(fileName, FileMode.Open, FileAccess.Read);
                sr = new System.IO.StreamReader(file);
                string xmlString = sr.ReadToEnd();
                sr.Close();
                file.Close();
                return Deserialize(xmlString);
            }
            finally {
                if ((file != null)) {
                    file.Dispose();
                }
                if ((sr != null)) {
                    sr.Dispose();
                }
            }
        }
        #endregion
 
   }
   /// <remarks/>
   [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Xml", "4.0.30319.34234")]
   [System.SerializableAttribute()]
   [System.Diagnostics.DebuggerStepThroughAttribute()]
   [System.ComponentModel.DesignerCategoryAttribute("code")]
   [System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
   public partial class REFMAIN
   {
      private REFMAINMAIN_LINE mAIN_LINEField;
      private uint idField;
      /// <remarks/>
      public REFMAINMAIN_LINE MAIN_LINE
      {
         get
         {
            return this.mAIN_LINEField;
         }
         set
         {
            this.mAIN_LINEField = value;
         }
      }
      /// <remarks/>
      [System.Xml.Serialization.XmlAttributeAttribute()]
      public uint ID
      {
         get
         {
            return this.idField;
         }
         set
         {
            this.idField = value;
         }
      }
   }
   /// <remarks/>
   [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Xml", "4.0.30319.34234")]
   [System.SerializableAttribute()]
   [System.Diagnostics.DebuggerStepThroughAttribute()]
   [System.ComponentModel.DesignerCategoryAttribute("code")]
   [System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
   public partial class REFMAINMAIN_LINE
   {
      private REFMAINMAIN_LINEMAIN_LINE mAIN_LINEField;
      /// <remarks/>
      public REFMAINMAIN_LINEMAIN_LINE MAIN_LINE
      {
         get
         {
            return this.mAIN_LINEField;
         }
         set
         {
            this.mAIN_LINEField = value;
         }
      }
   }
   /// <remarks/>
   [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Xml", "4.0.30319.34234")]
   [System.SerializableAttribute()]
   [System.Diagnostics.DebuggerStepThroughAttribute()]
   [System.ComponentModel.DesignerCategoryAttribute("code")]
   [System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
   public partial class REFMAINMAIN_LINEMAIN_LINE
   {
      private System.DateTime dATEField;
      private string cOMMENTField;
      /// <remarks/>
      [System.Xml.Serialization.XmlAttributeAttribute(DataType="date")]
      public System.DateTime DATE
      {
         get
         {
            return this.dATEField;
         }
         set
         {
            this.dATEField = value;
         }
      }
      /// <remarks/>
      [System.Xml.Serialization.XmlAttributeAttribute()]
      public string COMMENT
      {
         get
         {
            return this.cOMMENTField;
         }
         set
         {
            this.cOMMENTField = value;
         }
      }
   }
}
3) требуется заполнить xml файл примерный код функции:
        private void CreateXML(Dictionary<uint, string> myDataList)
        {
            string name = "MyName"; // -> name
            string action = "read"; // -> action
 
            REF myref = new REF(); // root element
 
            myref.name = name;
            myref.action = action;
 
            //mydate -> DATE
            DateTime mydate = new System.DateTime(DateTime.Now.Year, 1, 1, 0, 0, 0, 0);
 
            foreach (var mydt in myDataList)
            {
                //mydt.Key -> ID, mydt.Value -> COMMENT;
            }
 
            myref.Serialize();
            myref.SaveToFile(xmlfile);
        }
рут REF заполняется легко:
<?xml version="1.0" encoding="WINDOWS-1251"?>
<REF name="MyName" action="read">
не могу понять как заполнить остальные данные XML файл должен быть такой:
<?xml version="1.0" encoding="WINDOWS-1251"?>
<REF name="MyName" action="read">
	<MAIN ID="1">
		<MAIN_LINE>
			<MAIN_LINE DATE="2015-01-01" COMMENT=""/>
		</MAIN_LINE>
	</MAIN>
</REF>
Заранее спасибо за подсказки и помощь!
сделал, но почему-то сохраняется только последний элемент из списка:
private void CreateXML(Dictionary<uint, string> myDataList)
        {
            string name = "MyName"; // -> name
            string action = "read"; // -> action
 
            REF myref = new REF(); // root element
 
            myref.name = name;
            myref.action = action;
 
            //mydate -> DATE
            DateTime mydate = new System.DateTime(DateTime.Now.Year, 1, 1, 0, 0, 0, 0);
 
            foreach (var mydt in myDataList)
            {
                REFMAINMAIN_LINE refmainline = new REFMAINMAIN_LINE();
                refmainline.MAIN_LINE = new REFMAINMAIN_LINEMAIN_LINE();
                refmainline.MAIN_LINE.DATE = mydate;
                refmainline.MAIN_LINE.COMMENT= mydt.Value;
 
                REFMAIN refmain = new REFMAIN();
                refmain.REFMAINMAIN_LINE = refmainline;
                refmain.ID = mydt.Key;
 
                myref.MAIN = new REFMAIN[] { refmain };
            }
 
            myref.Serialize();
            myref.SaveToFile(xmlfile);
        }
в чем может быть проблема?

Решение задачи: «Заполнение XML по XSD»

textual
Листинг программы
private void CreateXML(Dictionary<uint, string> myDataList)
{
    string name = "MyName"; // -> name
    string action = "read"; // -> action
 
    REF myref = new REF(); // root element
 
    myref.name = name;
    myref.action = action;
 
    //mydate -> DATE
    DateTime mydate = new System.DateTime(DateTime.Now.Year, 1, 1, 0, 0, 0, 0);
 
    List<REFMAIN> list = new List<REFMAIN>();
 
    foreach (var mydt in myDataList)
    {
        REFMAINMAIN_LINE refmainline = new REFMAINMAIN_LINE();
        refmainline.MAIN_LINE = new REFMAINMAIN_LINEMAIN_LINE();
        refmainline.MAIN_LINE.DATE = mydate;
        refmainline.MAIN_LINE.COMMENT= mydt.Value;
 
        REFMAIN refmain = new REFMAIN();
        refmain.REFMAINMAIN_LINE = refmainline;
        refmain.ID = mydt.Key;
 
        list.Add(refmain);
    }
 
    myref.MAIN = list.ToArray();
 
    myref.Serialize();
    myref.SaveToFile(xmlfile);
}

ИИ поможет Вам:


  • решить любую задачу по программированию
  • объяснить код
  • расставить комментарии в коде
  • и т.д
Попробуйте бесплатно

Оцени полезность:

15   голосов , оценка 4.333 из 5