2016-02-23 230 views
2

我開始看XML(反)序列和我掙扎反序列化下面的XML反序列化XML屬性

<?xml version="1.0" encoding="utf-8" ?> 
<Reader> 
    <NewRecord value ="HH"/> 
    <FileTerminator value ="HHProgram"/> 
    <OutputFont value ="Courier"/> 
</Reader> 

分爲以下類

public class Reader 
{ 
    [XmlElement] 
    public string NewRecord; 
    [XmlElement] 
    public string FileTerminator; 
    [XmlElement] 
    public string OutputFont; 

} 

我無法引用以下XML按預期工作的每個元素的正確值屬性。

<?xml version="1.0" encoding="utf-8" ?> 
<LayoutReader> 
    <NewRecord>HH</NewRecord> 
    <FileTerminator>HHProgram</FileTerminator> 
    <OutputFont>Courier</OutputFont> 
</LayoutReader> 
+0

後者的作品沒有調整,因爲你有值的元素存在 –

回答

2

嘗試使用此代碼,它的工作原理與您的期望相同。你還可以添加其他屬性相同的方式

public class Reader 
{ 
    ... 
    [XmlElement("OutputFont")] 
    public ReaderItemOutputFont ReaderItem { get; set; } 
} 


[Serializable()] 
public class ReaderItemOutputFont 
{ 
    [XmlAttribute("value")] 
    public String OutputFont { get; set; } 
} 
0

這個工作對我來說 -

[XmlRoot] 
public class Reader 
{ 
    [XmlElement] 
    public NewRecord NewRecord; 

    [XmlElement] 
    public FileTerminator FileTerminator; 

    [XmlElement] 
    public OutputFont OutputFont; 
} 

public class NewRecord 
{ 
    [XmlAttribute] 
    public string value; 

} 

public class FileTerminator 
{ 
    [XmlAttribute] 
    public string value; 

} 

public class OutputFont 
{ 
    [XmlAttribute] 
    public string value; 
} 


var t = o.Deserialize("xml"); // works