Summary of three ways C generates XML

  • 2020-05-12 03:03:23
  • OfStack

1. I think it is the most primitive and basic one: using XmlDocument to write a node to an XML file, and then using XmlDocument to save the file.
First load the XML file to be written, but if there is none, create a new one.


            XmlDocument doc = new XmlDocument();
            try
            {
                doc.Load("new.xml");
            }
            catch
            {
                XmlTextWriter xtw = new XmlTextWriter("new.xml", Encoding.UTF8);
                // new XML file          
                xtw.WriteStartDocument();
                xtw.WriteStartElement("gnode");
                // gnode The root node                   
                xtw.WriteStartElement("myxm1");
                // gnode The element under the root node myxmls              
                xtw.WriteEndElement();
                xtw.WriteEndElement();
                xtw.WriteEndDocument();
                xtw.Close();
                doc.Load("new.xml");
            }
            XmlNode xn = doc.DocumentElement;
            // Find the root node       
            XmlElement xe = doc.CreateElement("myxml2");
            // Create an element under the root node, or an attribute, if any XmlAttribute ;   
            xe.InnerText = "hahaha";
            // Write text nodes (values) to child nodes       
            xn.AppendChild(xe);
            // The root node brings it in           
            doc.Save("new2.xml");
            // using XmlDocument Save the file 
        }

Note: when creating a new root node, WriteStartElement can only be nested, which means it can only have one root node.

2. Applied to the database, the database DataSet object values to generate XML file elements;


   using (SqlConnection con = new SqlConnection("Server=.;DataBase=HGSTUDY;uid=sa;pwd=yao"))
            {
                con.Open();
                SqlCommand command = new SqlCommand("select * from GL_STUDY", con);
                command.CommandType = CommandType.Text;
                DataSet ds = new DataSet("DATASET");
                //DATASET Will be XML The root node name in the file, otherwise the system will name it as NewDataSet       
                SqlDataAdapter sda = new SqlDataAdapter();
                sda.SelectCommand = command;
                sda.Fill(ds, "DATATABLE");
                //DATATABLE For the generated XML The name of the child node in the file, otherwise the system will name it as Table .     
                ds.WriteXml("dbxml.xml");
                // DataSet The method of WriteXml Write the data to XML Documents, that's all 1 Words. If not saved to a file, directly ds.GetXML()       
            }

3. Use XmlSerializer to convert the attribute values of the class to the element values of the XML file. Use one string as xmlAttribute or xmlElement in one XML document. [its elements or attributes are set by the definition of the class (xml serialization)]

using System;System.xml.Serialization;

3.1. Initialize 1 class and set the property value


[XmlRoot("Truck")]
                //---- Set up as a XML The root element name in    
        public Truck()    
        { }              
        [XmlAttribute("id")]
        //-------- Set up as a xml The properties in the      
        public int ID     
            {         
                get{return this._id;}  
                set { this._id = value; }    
            }       
        [XmlElement("chepai")]
        //------ Set up as a XML Element in (default)    
        public string cheID    
        {           
            get {
                return this._cheID;
            }         
            set {
                this._cheID = value;
            }        
        }        
        private int _id = 0;  
        private string _cheID = "";   

3.2. Create an XmlSerializer instance


class XXX {   
               XmlSerializer ser = new XmlSerializer(Type.GetType("forxml.truck"));    
               Truck tr = new Truck();      
               tr.ID = 1;     
               tr.cheID = " jiangxi A T34923";
           }

3.3.Serialize method -- completes serialization of the class

XmlTextWriter xtw = new XmlTextWriter("myxml.xml",Encoding.UTF8);

Create an XML file with XmlTextWriter
ser.Serialize(xtw, tr);
If you only want to display, you can directly ser.Serialize (Console.Out, tr);
}

Personal summary, here only described three methods, flexible application will be very good, direct input, or through the database or class can be. It can be used to generate XML in C#.


Related articles: