我正在尝试反序列化从 Moodle Web 服务收到的 XML 响应。
如果它具有不同的命名属性,例如 id、shortname、idnumber 等,我可以将其解析为 dotnet 对象。但它有一个 KEY 属性数组,其中实际字段名称作为值,并且在其中,还有另一个节点具有字段值.
这是一个示例:
<?xml version="1.0" encoding="UTF-8" ?>
<RESPONSE>
<MULTIPLE>
<SINGLE>
<KEY name="id">
<VALUE>2</VALUE>
</KEY>
<KEY name="shortname">
<VALUE>CS-101</VALUE>
</KEY>
<KEY name="fullname">
<VALUE>CS-101</VALUE>
</KEY>
<KEY name="enrolledusercount">
<VALUE>2</VALUE>
</KEY>
<KEY name="idnumber">
<VALUE></VALUE>
</KEY>
<KEY name="visible">
<VALUE>1</VALUE>
</KEY>
<KEY name="summary">
<VALUE><p>CS-101<br /></p></VALUE>
</KEY>
<KEY name="summaryformat">
<VALUE>1</VALUE>
</KEY>
<KEY name="format">
<VALUE>weeks</VALUE>
</KEY>
<KEY name="showgrades">
<VALUE>1</VALUE>
</KEY>
<KEY name="lang">
<VALUE></VALUE>
</KEY>
<KEY name="enablecompletion">
<VALUE>0</VALUE>
</KEY>
</SINGLE>
</MULTIPLE>
</RESPONSE>
我想将此 XML 解析为此类的对象:
class Course
{
public int id { get; set; }
public string shortname { get; set; } //short name of course
public string fullname { get; set; } //long name of course
public int enrolledusercount { get; set; } //Number of enrolled users in this course
public string idnumber { get; set; } //id number of course
public int visible { get; set; } //1 means visible, 0 means hidden course
public string summary { get; set; }
public int summaryformat { get; set; } //summary format (1 = HTML, 0 = MOODLE, 2 = PLAIN or 4 = MARKDOWN)
public string format { get; set; } //course format: weeks, topics, social, site
public int showgrades { get; set; } //true if grades are shown, otherwise false
public string lang { get; set; } //forced course language
public int enablecompletion { get; set; } //true if completion is enabled, otherwise false
}
有没有直接的方法,或者我应该为每个字段编写一个带有 switch case 的解析器方法?