c#:如何创建可序列化的c#类以反映具有动态子元素的XML文件?

时间:2012-09-24 09:25:27

标签: c# xml-serialization

有人可以建议如何创建一个c#类来反映以下XML结构示例吗?基本上,元素 Value 中的子元素可以包含 Integer String 元素。

<Preferences>
   <Preference>
      <Tag>CY3A</Tag>
      <Precedence>XML</Precedence>
      <Value>
         <Length>4</Length>
         <Integer>0</Integer>
      </Value>
   </Preference>    
   <Preference>
      <Tag>CYRV</Tag>
      <Precedence>XML</Precedence>
      <Value>
         <Length>16</Length>
         <String>0000 00 @00000</String>
      </Value>
   </Preference>
</Preferences>

我试图按如下方式定义类,但它并没有导致我正在寻找的东西。它会生成不需要的 d 元素。

public class ProgrammingConfiguration
{
   public int Version { get; set; }
   public preferences Preferences { get; set; }
}

public class preferences
{
   public preference Preference { get; set; }
}

public class preference
{
   public string Tag { get; set; }
   public string Precedence { get; set; }                                     
   public value Value { get; set; }
}

public class value
{
   [XmlElement]
   public int Length;

   [XmlElement(Type = typeof(Integer)),
    XmlElement(Type = typeof(HexBinary))]
   public object datafield;
}

public class Integer
{          
   public string d;            
}  

public class String
{            
   public string d;
}        

1 个答案:

答案 0 :(得分:0)

我通常会创建一个xsd,然后使用xsd.exe工具从xsd创建一个.cs类文件。

//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.269
//
//     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=4.0.30319.1.
// 


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

    private PreferencesPreference[] itemsField;

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

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

    private string tagField;

    private string precedenceField;

    private PreferencesPreferenceValue[] valueField;

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

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

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

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

    private string lengthField;

    private string stringField;

    private string integerField;

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

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

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

xsd.exe是Visual Studio附带的实用程序....

查看http://quickstart.developerfusion.co.uk/quickstart/howto/doc/xmlserialization/XSDFromCls.aspx

但你也可以从XML中做到这一点

c:\temp>xsd test.xml
Microsoft (R) Xml Schemas/DataTypes support utility
[Microsoft (R) .NET Framework, Version 4.0.30319.1]
Copyright (C) Microsoft Corporation. All rights reserved.
Writing file 'c:\temp\test.xsd'.

c:\temp>xsd test.xsd /classes
Microsoft (R) Xml Schemas/DataTypes support utility
[Microsoft (R) .NET Framework, Version 4.0.30319.1]
Copyright (C) Microsoft Corporation. All rights reserved.
Writing file 'c:\temp\test.cs'.

要解决字符串与整数问题,可以在xsd中添加xs:choice字段,这将生成一个“Item”,然后可以根据需要将其转换为Int或String。看看http://msdn.microsoft.com/en-us/library/exchange/bb426064(v=exchg.140).aspx

<xs:complexType name="FindItemParentType">
  <xs:choice>
    <xs:element name="Items" type="t:ArrayOfRealItemsType"/>
    <xs:element name="Groups" type="t:ArrayOfGroupedIetmsType"/>
  </xs:choice>
  <xs:attributeGroup ref="t:FindResponsePagingAttributes"/>
</xs:complexType>

FindItemParentType fipt = new FindItemParentType();
object obj = fipt.Item;
if (obj is ArrayOfGroupedItemsType)
{
    ArrayOfGroupedItemsType groupedItems = (obj as ArrayOfGroupedItemsType);
    //TODO: Write code to handle grouped items.
}
else if (obj is ArrayOfRealItemsType)
{
    ArrayOfRealItemsType items = (obj as ArrayOfRealItemsType);
    //TODO: Write code to handle items.
}
相关问题