XML to C# class
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</开发者_JAVA百科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#?
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; }
}
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")
};
you can try this: http://www.switchonthecode.com/tutorials/csharp-tutorial-xml-serialization
精彩评论