2010-09-15 73 views
0

我有自定義對象類,我想連載:如何爲Object自定義XML序列化輸出?

public partial class CustomObject 
{    
    public List<CustomProperty> Properties; 
} 

public class CustomProperty 
{    
    public object Value;     
    [XmlAttribute] 
    public string Name; 
} 

// some class to be used as a value for CustomProperty 
public class Person 
{ 
    public string Name; 
    public string Surname; 
    public string Photo; 
    [XmlAttribute] 
    public int Age; 
} 

目前XML序列化輸出是這樣的:

<CustomObject> 
    <Properties> 
    <CustomProperty Name="Employer"> 
     <Value p6:type="Person" xmlns:p6="http://www.w3.org/2001/XMLSchema-instance" Age="30"> 
     <Name>John</Name> 
     <Surname>Doe</Surname> 
     <Photo>photos/John.jpg</Photo> 
     </Value> 
    </CustomProperty> 
    <CustomProperty Name="Desc"> 
     <Value xmlns:q1="http://www.w3.org/2001/XMLSchema" p7:type="q1:string" xmlns:p7="http://www.w3.org/2001/XMLSchema-instance">some text</Value> 
    </CustomProperty> 
    </Properties> 
</CustomObject> 

首先我想刪除的命名空間和所有的噪音。

最終的結果應該是這樣的:

<CustomObject> 
    <Properties> 
    <CustomProperty Name="Employer"> 
     <Person Age="30"> 
     <Name>John</Name> 
     <Surname>Doe</Surname> 
     <Photo>photos/John.jpg</Photo> 
     </Person> 
    </CustomProperty> 
    <CustomProperty Name="Desc"> 
     <string>some text</string> 
    </CustomProperty> 
    </Properties> 
</CustomObject> 

或者這樣:

<CustomObject> 
    <Properties> 
    <Person Name="Employer" Age="30"> 
     <Name>John</Name> 
     <Surname>Doe</Surname> 
     <Photo>photos/John.jpg</Photo> 
    </Person> 
    <string Name="Desc"> 
     some text 
    </string> 
    </Properties> 
</CustomObject> 

如何才能XmlSerializer的,以這樣的輸出呢?

回答

1

你也可以指定元素的名稱,以確保該類型正確處理:

[System.Xml.Serialization.XmlElementAttribute("files", typeof(Files))] 
[System.Xml.Serialization.XmlElementAttribute("metrics", typeof(Metrics))] 
public object[] Items { get; set; } 
+0

這會得到第一個想要的情況。謝謝! – JBeurer 2010-09-15 06:13:16

1

看看XmlElement屬性 - 這可能至少部分解決您的問題。從MSDN:

public class Things { 
    [XmlElement(DataType = typeof(string)), 
    XmlElement(DataType = typeof(int))] 
    public object[] StringsAndInts; 
} 

會產生

<Things> 
    <string>Hello</string> 
    <int>999</int> 
    <string>World</string> 
</Things> 
+0

它看起來像MSDN實際上在示例中有一個錯誤,我認爲它應該是[XmlElement(Type = typeof(string))] [XmlElement(Type = typeof(int))],因爲DataType是字符串。但是,這也有效!謝謝! – JBeurer 2010-09-15 06:16:05

1

你可以刪除命名空間像

  StringBuilder sb = new StringBuilder(); 
      XmlWriter writer = XmlWriter.Create(sb); 
      XmlSerializer serializer = new XmlSerializer(typeof(WSOpenShipments), myns); 
      var ns = new XmlSerializerNamespaces(); 
      ns.Add(string.Empty, ""); 
      serializer.Serialize(writer, OS, ns); 
      xmlString = sb.ToString(); 

usse this - ns.Add(string.Empty,「」);