从不同元素反序列化具有相同名称的xml属性

时间:2016-02-23 12:46:54

标签: c# xml deserialization

我开始关注XML(反)序列化,我正在努力反序列化以下XML

/path/to/my/package/man: Sections \title, and \name must exist and be unique in Rd files 

进入以下课程

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

我无法引用以下XML按预期工作的每个元素的正确值属性。

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

}

2 个答案:

答案 0 :(得分:2)

尝试使用此代码,它可以按预期工作。你也可以用同样的方式添加其他属性

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


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

答案 1 :(得分: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