How to convert complex XML to .NET Class? [duplica

2019-04-02 04:00发布

问题:

This question already has an answer here:

  • Convert XML String to Object 12 answers

I have this XML and just wondering how I can convert into C# class?

<?xml version="1.0" encoding="utf-8"?>
<TextScrollerItems xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

    <Item type="text" ID="234">
     <Text Color="Blue">
       Sample text...
     </Text>
    </Item>

    <Item type="image" ID="2456">
        <Image>
          clientLogo.png
        </Image>
    </Item>

    </TextScrollerItems>

回答1:

give a try to the XSD.exe tool shipped with Visual Studio. Here's some docs: http://www.codeproject.com/Articles/11317/From-XML-to-Strong-Types-in-C



回答2:

I'd recommend XML serialization using XmlSerializer. Basically, you need to create classes which correspond to the XML structure and the XmlSerializer takes care of the rest. If you have control over the XML format, it is better to first create the classes and than generate a sample xml via XmlSerializer which you can than fill with real data.



回答3:

Microsoft provide this free tool for generating classes from schema.



回答4:

Transforming class instances to Xml and the other way around is called serialization/deserialization. You'll find a lot of articles on the internet on that topic, a good start here.



回答5:

The best solution is this one:

http://www.codeproject.com/Articles/11317/From-XML-to-Strong-Types-in-C

  1. Write an XML structure (XML)
  2. Create XSD file from XML file
  3. Create C# classes from XSD file

XML

<?xml version="1.0" encoding="utf-8"?>
<TextScrollerItems xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

    <Item type="text" ID="234">
     <Text Color="Blue">
       Sample text...
     </Text>
    </Item>

    <Item type="image" ID="2456">
        <Image>
          clientLogo.png
        </Image>
    </Item>

    </TextScrollerItems>

XSD

<?xml version="1.0" encoding="utf-8"?>
<xs:schema id="TextScrollerItems" xmlns="" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
  <xs:element name="TextScrollerItems" msdata:IsDataSet="true" msdata:UseCurrentLocale="true">
    <xs:complexType>
      <xs:choice minOccurs="0" maxOccurs="unbounded">
        <xs:element name="Item">
          <xs:complexType>
            <xs:sequence>
              <xs:element name="Image" type="xs:string" minOccurs="0" msdata:Ordinal="0" />
              <xs:element name="Text" nillable="true" minOccurs="0" maxOccurs="unbounded">
                <xs:complexType>
                  <xs:simpleContent msdata:ColumnName="Text_Text" msdata:Ordinal="1">
                    <xs:extension base="xs:string">
                      <xs:attribute name="Color" type="xs:string" />
                    </xs:extension>
                  </xs:simpleContent>
                </xs:complexType>
              </xs:element>
            </xs:sequence>
            <xs:attribute name="type" type="xs:string" />
            <xs:attribute name="ID" type="xs:string" />
          </xs:complexType>
        </xs:element>
      </xs:choice>
    </xs:complexType>
  </xs:element>
</xs:schema>

C# classes

//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:2.0.50727.5448
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

using System.Xml.Serialization;

// 
// This source code was auto-generated by xsd, Version=2.0.50727.3038.
// 


/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.3038")]
[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 TextScrollerItems {

    private TextScrollerItemsItem[] itemsField;

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute("Item", Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
    public TextScrollerItemsItem[] Items {
        get {
            return this.itemsField;
        }
        set {
            this.itemsField = value;
        }
    }
}

/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
public partial class TextScrollerItemsItem {

    private string imageField;

    private TextScrollerItemsItemText[] textField;

    private string typeField;

    private string idField;

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
    public string Image {
        get {
            return this.imageField;
        }
        set {
            this.imageField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute("Text", Form=System.Xml.Schema.XmlSchemaForm.Unqualified, IsNullable=true)]
    public TextScrollerItemsItemText[] Text {
        get {
            return this.textField;
        }
        set {
            this.textField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string type {
        get {
            return this.typeField;
        }
        set {
            this.typeField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string ID {
        get {
            return this.idField;
        }
        set {
            this.idField = value;
        }
    }
}

/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
public partial class TextScrollerItemsItemText {

    private string colorField;

    private string valueField;

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string Color {
        get {
            return this.colorField;
        }
        set {
            this.colorField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlTextAttribute()]
    public string Value {
        get {
            return this.valueField;
        }
        set {
            this.valueField = value;
        }
    }
}


标签: c# .net xml class