2009-08-04 113 views
8

我正在使用VSTS2008 + C#+ .Net 3.0。我使用下面的代碼來序列化XML,並且我的對象包含數組類型屬性,但是生成了我想從生成的XML文件中刪除的一些附加元素的層(在我的示例中,MyInnerObject和MyObject)。有任何想法嗎?從XML序列化陣列中刪除包裝元素

電流生成的XML文件,

<?xml version="1.0"?> 
<MyClass xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> 
    <MyObjectProperty> 
    <MyObject> 
     <MyInnerObjectProperty> 
     <MyInnerObject> 
      <ObjectName>Foo Type</ObjectName> 
     </MyInnerObject> 
     </MyInnerObjectProperty> 
    </MyObject> 
    </MyObjectProperty> 
</MyClass> 

預期的XML文件,

<?xml version="1.0"?> 
<MyClass xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> 
    <MyObjectProperty> 
     <MyInnerObjectProperty> 
      <ObjectName>Foo Type</ObjectName> 
     </MyInnerObjectProperty> 
    </MyObjectProperty> 
</MyClass> 

當前代碼,

public class MyClass 
{ 
    private MyObject[] _myObjectProperty; 

    [XmlArrayItemAttribute(IsNullable=false)] 
    public MyObject[] MyObjectProperty 
    { 
     get 
     { 
      return _myObjectProperty; 
     } 
     set 
     { 
      _myObjectProperty = value; 
     } 
    } 
} 
public class MyObject 
{ 
    private MyInnerObject[] _myInnerObjectProperty; 

    [XmlArrayItemAttribute(IsNullable = false)] 
    public MyInnerObject[] MyInnerObjectProperty 
    { 
     get 
     { 
      return _myInnerObjectProperty; 
     } 
     set 
     { 
      _myInnerObjectProperty = value; 
     } 
    } 
} 

public class MyInnerObject 
{ 
    public string ObjectName; 
} 

public class Program 
{ 
    static void Main(string[] args) 
    { 
     XmlSerializer s = new XmlSerializer(typeof(MyClass)); 
     FileStream fs = new FileStream("foo.xml", FileMode.Create); 
     MyClass instance = new MyClass(); 
     instance.MyObjectProperty = new MyObject[1]; 
     instance.MyObjectProperty[0] = new MyObject(); 
     instance.MyObjectProperty[0].MyInnerObjectProperty = new MyInnerObject[1]; 
     instance.MyObjectProperty[0].MyInnerObjectProperty[0] = new MyInnerObject(); 
     instance.MyObjectProperty[0].MyInnerObjectProperty[0].ObjectName = "Foo Type"; 
     s.Serialize(fs, instance); 

     return; 
    } 
} 

回答

14

而不是

[XmlArrayItemAttribute] 

使用:

[XmlElement] 

要在未來,你可以運行想出解決辦法(從VS命令提示符):

xsd.exe test.xml 
xsd.exe /classes test.xsd 

這產生test.cs中,包含XML序列化的類,基於xml。如果你有一個.xsd文件,這個效果會更好。

+0

謝謝Sander,你的解決方案可以工作。你能否介紹一下爲什麼使用XmlArrayItemAttribute會影響結果XML?爲什麼XmlElement的作品? – George2 2009-08-04 14:13:51