XML to C# class

耗尽温柔 提交于 2020-01-11 06:28:10

问题


Can anyone give me some advice? An API I'm consulting generates a pattern like this:

<?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>

How can I get all messages from this in C#?


回答1:


See Attributes that control XML Serialization, e.g.:

[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 { .. }

etc


Also I see the common element, <Signature />, thus you can introduce a parent class:

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



回答2:


You could use Linq to XML to load the xml into anonymous objects, or you could create an object to load with the values.

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")
    };



回答3:


you can try this: http://www.switchonthecode.com/tutorials/csharp-tutorial-xml-serialization



来源:https://stackoverflow.com/questions/6075343/xml-to-c-sharp-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!