2012-07-30 130 views
0

這裏是我的xml文件看起來像:XmlSerializer的自定義對象

我試圖用XSD來爲我的對象類,但不知何故,當我試圖反序列化沒有奏效。我需要列是一個字符串數組,我的類(對象)應該是什麼,以便它可以反序列化xml。

<ArrayOfDirective> 
<Directive> 
<TestCaseName>RunSqlCar</TestCaseName> 
<Action>IgnoreColumn</Action> 
<Columns> 
<ColumnName>value1</ColumnName> 
<ColulmnName>value2</ColulmnName> 
</Columns> 
<Description>These columns never match becuase IDs are different always.</Description>  
</Directive> 
</ArrayOfDirective> 

錯誤: 錯誤讀取C:\ Directives.xml:有XML文檔中的一個錯誤(2,2)

+0

請編輯您的問題,而不是評論它。 – Stu 2012-07-30 23:22:50

+0

這是正確的,我在問題中有。首先,我想我錯過了添加該部分。 – Maurh 2012-07-30 23:24:47

+0

你們想看看xsd生成的類嗎? – Maurh 2012-07-30 23:26:08

回答

0

你的數據,使用XmlSerializer的序列化,將是這樣的:

<?xml version="1.0" encoding="utf-8"?> 
<ArrayOfDirective xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> 
    <Directives> 
    <Directive> 
     <TestCaseName>RunSqlCar</TestCaseName> 
     <Action>IgnoreColumn</Action> 
     <Columns> 
     <Column> 
      <ColumnName>value1</ColumnName> 
     </Column> 
     <Column> 
      <ColumnName>value2</ColumnName> 
     </Column> 
     </Columns> 
     <Description>These columns never match because IDs are different always.</Description> 
    </Directive> 
    </Directives> 
</ArrayOfDirective> 

這些是序列化到上述XML的示例類。

class Program 
{ 
    static void Main(string[] args) 
    { 
     ArrayOfDirective directives = new ArrayOfDirective(); 

     Directive directive = new Directive("RunSqlCar", "IgnoreColumn", 
       "These columns never match because IDs are different always."); 

     directive.Columns.Add(new Column("value1")); 
     directive.Columns.Add(new Column("value2")); 

     directives.Directives.Add(directive); 

     XmlSerializer ser = new XmlSerializer(typeof(ArrayOfDirective)); 
     using (StreamWriter sw = File.CreateText("c:\\directives_generated.xml")) 
     { 
      ser.Serialize(sw, directives); 
     } 
    } 
} 

[Serializable] 
public class ArrayOfDirective 
{ 
    public List<Directive> Directives { get; set; } 

    public ArrayOfDirective() 
    { 
     Directives = new List<Directive>(); 
    } 
} 

[Serializable] 
public class Directive 
{ 
    public string TestCaseName { get; set; } 
    public string Action { get; set; } 
    public List<Column> Columns { get; set; } 
    public string Description { get; set; } 

    public Directive(string testCaseName, string action, string description) 
    { 
     TestCaseName = testCaseName; 
     Action = action; 
     Description = description; 
     Columns = new List<Column>(); 
    } 

    public Directive() 
    { 
    } 
} 

[Serializable] 
public class Column 
{ 
    public string ColumnName { get; set; } 

    public Column(string columnName) 
    { 
     ColumnName = columnName; 
    } 

    public Column() 
    { 
    } 
} 
+0

我不想生成XML文件,而是將XML讀入使用XMLserializer.deserialize的對象列表 – Maurh 2012-07-31 16:17:43