XML到C#类

时间:2011-05-20 17:06:54

标签: c# .net xml serialization xml-serialization

有人能给我一些建议吗? 我正在咨询的API生成这样的模式:

<?xml version="1.0"?>
<ChatXMLResult>
    <Generator>AppServer.network.lcpdfr.com</Generator>
    <Version>1000</Version>
    <Time>1305910998</Time>
    <Signature>a0f1f6bea66f75de574babd242e68c47</Signature>
    <FilteredResultSet>1</FilteredResultSet>
    <Messages>
        <Message>
            <ID>1</ID>
            <UID>9</UID>
            <DisplayName>Jay</DisplayName>
            <UserName>jaymac407</UserName>
            <Time>1305900497</Time>
            <Area>Masterson St</Area>
            <Message>Test</Message>
            <TargettedMessage>false</TargettedMessage>
            <Targets>
                <Target>#Global Chat#</Target>
            </Targets>
            <Signature>1cfdff1aaa520348d0a62c87ae9717d3</Signature>
        </Message>
    </Messages>
</ChatXMLResult>

如何在C#中获取此消息?

3 个答案:

答案 0 :(得分:4)

Attributes that control XML Serialization,例如:

[XmlRoot("ChatXMLResult")] 
public class Chat
{
    [XmlElement("Signature")] // optional 
    public string Signature { get; set; }

    [XmlArray]
    [XmlArrayItem(typeof(Message), ElementName="Message")]
    public Message[] Messages { get; set; }
}

public class Message { .. }


此外,我看到了公共元素<Signature />,因此您可以引入父类:

public abstract class SignedObject
{
    public string Signature { get; set; }
}

答案 1 :(得分:4)

您可以使用Linq to XML将xml加载到匿名对象中,或者您可以创建一个要加载值的对象。

var doc = XDocument.Parse(xml);

var messages = from m in doc.Descendants("Message")
    select new {
        ID = (string)m.Element("ID"),
        UID = (string)m.Element("UID"),
        DisplayName = (string)m.Element("DisplayName"),
        // etc
        Signature = (string)m.Element("Signature")
    };

答案 2 :(得分:1)