2016-09-22 50 views
0

我序列化導致該輸出的結構:.NET在一個緊湊的,易於理解的方式序列化XML

<NachrichtenKonfiguration> 
    <Elemente> 
    <Element> 
     <Typ>Bool</Typ> 
     <Bezeichnung>Gut</Bezeichnung> 
    </Element> 
    <Element> 
     <Typ>Int</Typ> 
     <Bezeichnung>Dauer</Bezeichnung> 
    </Element> 
    </Elemente> 
    <Name>Teiledaten</Name> 
</NachrichtenKonfiguration> 

,我想這是相當類似這樣的:

<NachrichtenKonfiguration Name="Teiledaten"> 
    <Elemente> 
    <Element Typ="Bool" Bezeichnung="Gut"/> 
    <Element Typ="Int" Bezeichnung="Schleifdauer"/> 
    </Elemente> 
</NachrichtenKonfiguration> 

是否有可能使XmlSerialzer/XmlWriter做到這一點(使用屬性,而不是嵌套元素)?

問候,

+4

是的,這是可能的。你有沒有嘗試過什麼? –

+3

[如何將XmlDocument序列化爲格式良好的可讀XML?](http://stackoverflow.com/questions/17101817/how-to-serialize-an-xmldocument-to-a-well- formatted-human-readable-xml) –

+2

@JayGould他不在尋找Identation。他正在尋找爲元素添加屬性的代碼,而不是元素的嵌套元素。 –

回答

2

好,我知道了,你只需要在相應的聲明添加[XmlAttribute - 標籤。

以下是操作方法。如果你有一個名爲「Person」的類,你必須在這兩個屬性,寫這樣的代碼:

[Serializable] 
public class Person 
{ 
    [XmlAttribute] 
    public int Age; 
    [XmlAttribute] 
    public string Name; 

    public Person() 
    { 

    } 
} 

當序列化(設置爲縮進線的XmlWriter設置)以上在該XML代碼結構的結果:

<Person Age="21" Name="Stacky" /> 
+0

你可以顯示代碼嗎? –

+0

當然可以。添加它。 – Ravior