2016-10-20 176 views
0

我正試圖用xml屬性來解決一個難題。問題是,我們已經有了廣泛使用的文件通過這種結構,從我不能偏離使用xml屬性創建XML結構

<CONFIGS> 
    <CONFIG> 
    <NAME>c1</NAME> 
    <DB> 
     <VAL1>v1</VAL1> 
     <VAL2>v2</VAL2> 
     <VAL3>v3</VAL3> 
    </DB> 
    </CONFIG> 
    <CONFIG> 
    <NAME>c2</NAME> 
    <DB> 
     <VAL1>v1</VAL1> 
     <VAL2>v2</VAL2> 
     <VAL3>v3</VAL3> 
    </DB> 
    </CONFIG> 
</CONFIGS> 

我創建這個C#代碼

// master class 
[XmlRoot(ElementName = "CONFIGS")] 
public class MyConfigs 
{ 

    [XmlArrayItem(ElementName = "CONFIG", Type = typeof(MyConfigSchema))] 
    public MyConfigSchema[] Schemas { get; set; } 
} 

// I should have array of these 
public class MyConfigSchema 
{ 

    [XmlElement(DataType = "string", ElementName = "NAME")] 
    public string Name { get; set; } 

    [XmlElement(ElementName = "DB", Type = typeof(Db))] 
    public Db Config { get; set; } 

    // this element is single and has subelements 
    public class Db 
    { 

     [XmlElement(DataType = "string", ElementName = "VAL1")] 
     public string Val1 { get; set; } 

     [XmlElement(DataType = "int", ElementName = "VAL2")] 
     public int Val2 { get; set; } 

     [XmlElement(DataType = "string", ElementName = "VAL3")] 
     public string Val3 { get; set; } 

    } 
} 

// Writing 
using (var writer = new FileStream(testfile, FileMode.Create)) 
     { 
      var ser = new XmlSerializer(typeof(MyConfigs)); 
      ser.Serialize(writer, confFileObj); 
      writer.Close(); 
     } 

這裏是我的問題 - 它寫入以下輸出,這幾乎是我所需要的,但在那裏它寫道我不能有<Schemas>. . . </Schemas>

<CONFIGS> --<Schemas>-- <CONFIG> <NAME>c1</NAME> <DB> <VAL1>v1</VAL1> <VAL2>v2</VAL2> <VAL3>v3</VAL3> </DB> </CONFIG> <CONFIG> <NAME>c2</NAME> <DB> <VAL1>v1</VAL1> <VAL2>v2</VAL2> <VAL3>v3</VAL3> </DB> </CONFIG> --</Schemas>-- </CONFIGS>

是否存在的擺脫<Schemas>. . . </Schemas>的方法嗎?

回答

1

看起來我剛剛解決了它。我從來沒有見過這個,看了MSDN,因此我沒有嘗試它。但我想,而不是這個

[XmlArrayItem(ElementName = "CONFIG", Type = typeof(MyConfigSchema))] 
public MyConfigSchema[] Schemas { get; set; } 

做到這一點

[XmlElement(ElementName = "CONFIG", Type = typeof(MyConfigSchema))] 
public MyConfigSchema[] Schemas { get; set; } 

代替XmlArrayItem我放在XmlElement和它的工作。我不知道可以使用純元素屬性標記List或數組。