The structure and type of mapping XML depth analysis.

Recommended for you: Get network issues from WhatsUp Gold. Not end users.

 

Extensible markup language (Extensible Markup Language, XML), used to mark the electronic file which has structural markup language, can be used to tag data, the data type is defined, is a allows the user to define their markup language as the source language. XML is the Standard Generalized Markup Language (SGML) subset, very suitable for Web transmission. XML provides a uniform method for describing and exchanging structured data is independent of the application or the supplier. I often use it to save some data, or some configuration parameters.

     Element nodes

     Node attribute 

     Node text

     By default (no Attribute), the field or property types, will generate XmlElement.

     If you want the type of property or field to generate XmlAttribute, need to suggest that [XmlAttribute] in the type of member.  

public class Class2
{
    [XmlAttribute]
    public int IntValue { get; set; }
    [XmlElement]
    public string StrValue { get; set; }
}

     If you want the type of property or field to generate InnerText, need to suggest that [XmlText] in the type of member.  

public class Class3
{
    [XmlAttribute]
    public int IntValue { get; set; }
    [XmlText]
    public string StrValue { get; set; }
}

     If you want the type of property or field to generate InnerText, need to suggest that [XmlText] in the type of member.

[XmlType("c4")]
public class Class4
{
    [XmlAttribute("id")]
    public int IntValue { get; set; }
    [XmlElement("name")]
    public string StrValue { get; set; }
}

Arrays and lists can serialize, if you want to rename the root node name, you need to create a new type to realize. The root node rename need [XmlRoot] to point out.

[XmlRoot("c4List")]
public class Class4List : List<Class4> { }

Arrays and lists are serialized, the default will generate a node according to type in the name of the data member, list item will generate a child node, if you want to rename, can use [XmlArrayItem] and [XmlArray] to achieve. Also can not directly generates a list of [XmlElement] controlled by the parent node.  

public class Root
{
    public Class3 Class3 { get; set; }
    [XmlArrayItem("c2")]
    [XmlArray("cccccccccccc")]
    public List<Class2> List { get; set; }
}
public class Root
{
    public Class3 Class3 { get; set; }
    [XmlElement("c2")]
    public List<Class2> List { get; set; }
}

     The elements of the list can be the same type, also can not the same type (a type of the derived class). Multiple [XmlArrayItem also specified as a list member (typeof (XXX))] can be various derived types to achieve mixed together output.  

<?xml version="1.0" encoding="utf-8"?>
<XRoot xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <List>
        <x1 aa="1" bb="2" />
        <x1 aa="3" bb="4" />
        <x2>
            <cc>ccccccccccc</cc>
            <dd>dddddddddddd</dd>
        </x2>
    </List>
</XRoot>
public class XBase { }
[XmlType("x1")]
public class X1 : XBase
{
    [XmlAttribute("aa")]
    public int AA { get; set; }
    [XmlAttribute("bb")]
    public int BB { get; set; }
}
[XmlType("x2")]
public class X2 : XBase
{
    [XmlElement("cc")]
    public string CC { get; set; }

    [XmlElement("dd")]
    public string DD { get; set; }
}
public class XRoot
{
    [XmlArrayItem(typeof(X1)),
    XmlArrayItem(typeof(X2))]
    public List<XBase> List { get; set; }
}

     By default, all public data member types (properties, fields) in the serialization can be output, if you want to exclude certain members, [XmlIgnore] can be used to indicate.

public class TestIgnore
{
    [XmlIgnore]    // This property will not participate in serialization
    public int IntValue { get; set; }
    public string StrValue { get; set; }
    public string Url;
}

     Use Order to specify the ordering of the elements.

public class TestIgnore
{
    [XmlElement(Order = 1)]
    public string StrValue { get; set; }
    [XmlElement(Order = 2)]
    public string Url;
}

     If the XML is obtained by the type of serialization, then deserialize the calling code is very simple, on the contrary, if want to face a no type of XML, we need to design a (or some) type, which is a process of reverse deduction, please refer to the following steps:

  1. First analysis of the XML structure, the type definition and matching.
  2. If the XML structure has a nested hierarchy, you need to define a plurality of types and matching.
  3. The definition of a specific type (XML structure under a hierarchy), please refer to the table below.  

     If only to save and read and don't care about the structure of the XML file, you can use serializable mode to read and write XML, this operation is quite simple.

// 1 first to create or obtain a data object
Order order = GetOrderById(123);
// The 2 generation with serialization method XML
string xml = XmlHelper.XmlSerialize(order, Encoding.UTF8);
// 3 read data from XML and generate object
Order order2 = XmlHelper.XmlDeserialize<Order>(xml, Encoding.UTF8);
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using System.IO;
using System.Xml;


public static class XmlHelper {

        /// <summary>
        /// Serialize an object
        /// </summary>
        private static void XmlSerializeInternal(Stream stream, object o, Encoding encoding)
        {
            if( o == null )
                throw new ArgumentNullException("o");
            if( encoding == null )
                throw new ArgumentNullException("encoding");
            XmlSerializer serializer = new XmlSerializer(o.GetType());
            XmlWriterSettings settings = new XmlWriterSettings();
            settings.Indent = true;
            settings.NewLineChars = "\r\n";
            settings.Encoding = encoding;
            settings.IndentChars = "    ";
            using( XmlWriter writer = XmlWriter.Create(stream, settings) ) {
                serializer.Serialize(writer, o);
                writer.Close();
            }
        }
        /// <summary>
        /// Serialize an object to a XML string
        /// </summary>
        /// <param name="o">The object to be serialized</param>
        /// <param name="encoding">Coding method</param>
        /// <returns>The XML string serialization</returns>
        public static string XmlSerialize(object o, Encoding encoding)
        {
            using( MemoryStream stream = new MemoryStream() ) {
                XmlSerializeInternal(stream, o, encoding);
                stream.Position = 0;
                using( StreamReader reader = new StreamReader(stream, encoding) ) {
                    return reader.ReadToEnd();
                }
            }
        }
        /// <summary>
        /// An object by XML serialization way to write to a file
        /// </summary>
        /// <param name="o">The object to be serialized</param>
        /// <param name="path">Save the file path</param>
        /// <param name="encoding">Coding method</param>
        public static void XmlSerializeToFile(object o, string path, Encoding encoding)
        {
            if( string.IsNullOrEmpty(path) )
                throw new ArgumentNullException("path");
            using( FileStream file = new FileStream(path, FileMode.Create, FileAccess.Write) ) {
                XmlSerializeInternal(file, o, encoding);
            }
        }
        /// <summary>
        /// Deserialize the object from the XML string
        /// </summary>
        /// <typeparam name="T">Results the object type</typeparam>
        /// <param name="s">Contains the XML string object</param>
        /// <param name="encoding">Coding method</param>
        /// <returns>The object deserialization obtained</returns>
        public static T XmlDeserialize<T>(string s, Encoding encoding)
        {
            if( string.IsNullOrEmpty(s) )
                throw new ArgumentNullException("s");
            if( encoding == null )
                throw new ArgumentNullException("encoding");
            XmlSerializer mySerializer = new XmlSerializer(typeof(T));
            using( MemoryStream ms = new MemoryStream(encoding.GetBytes(s)) ) {
                using( StreamReader sr = new StreamReader(ms, encoding) ) {
                    return (T)mySerializer.Deserialize(sr);
                }
            }
        }
        /// <summary>
        /// To read a file, and deserialize objects according to XML mode. 
        /// </summary>
        /// <typeparam name="T">Results the object type</typeparam>
        /// <param name="path">The file path</param>
        /// <param name="encoding">Coding method</param>
        /// <returns>The object deserialization obtained</returns>
        public static T XmlDeserializeFromFile<T>(string path, Encoding encoding)
        {
            if( string.IsNullOrEmpty(path) )
                throw new ArgumentNullException("path");
            if( encoding == null )
                throw new ArgumentNullException("encoding");
            string xml = File.ReadAllText(path, encoding);
            return XmlDeserialize<T>(xml, encoding);
        }
    }

 

 

 

 

 

 

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download

Posted by Spark at November 18, 2013 - 11:13 PM