使用RestSharp反序列化:XML属性转换为POCO类
Let's break this down into two straightforward parts: defining your POCO classes to perfectly match the XML structure, and then using RestSharp to handle deserialization smoothly.
Step 1: Complete Your POCO Classes
Your existing classes are off to a great start—we just need to properly handle the id attribute on the TRANSACTION element. Here's the full, annotated set of classes:
using System.Xml.Serialization; public class CONTENT { // Matches the root <SEND_SMS_SUCCESS> element inside <CONTENT> public SEND_SMS_SUCCESS SEND_SMS_SUCCESS { get; set; } } public class SEND_SMS_SUCCESS { // Maps to the <TRANSACTION> element; the attribute is redundant here since the property name matches the element name, but it's safe to keep [XmlElement("TRANSACTION")] public TRANSACTION TRANSACTION { get; set; } // Directly maps to <VALID_SMS_COUNT> (case-sensitive match) public int VALID_SMS_COUNT { get; set; } // Directly maps to <INVALID_SMS_COUNT> public int INVALID_SMS_COUNT { get; set; } } public class TRANSACTION { // Critical: This maps the "id" attribute of the <TRANSACTION> element (not a child element) [XmlAttribute("id")] public string Id { get; set; } // Swap to int if you're 100% sure the ID will always be a numeric value }
Key notes:
- Use
[XmlAttribute("id")]for the transaction ID because it’s an attribute in the XML, not a child element. - The property names exactly match the XML element names (case-sensitive), so no extra
XmlElementattributes are needed unless you want to use different C# naming conventions (like camelCase properties withXmlElementpointing to uppercase elements). - Pick
stringorintfor theIdproperty based on whether the API consistently returns a numeric ID.
Step 2: Deserializing with RestSharp
RestSharp has built-in XML deserialization support via XmlSerializer. Here are two common scenarios you’ll encounter:
Scenario 1: Deserialize from an API Response
If you’re making a request to the SMS API and receiving this XML as a response:
using RestSharp; // Initialize RestClient with your API's base URL var client = new RestClient("https://your-sms-api-domain.com"); // Create a request (adjust method and endpoint to match your API's requirements) var request = new RestRequest("/send-sms", Method.Post); // Add any required headers, parameters, or request body request.AddHeader("Content-Type", "application/xml"); request.AddXmlBody(yourSmsRequestObject); // Use this if you're sending an XML payload // Execute the request and automatically deserialize to your CONTENT class var response = client.Execute<CONTENT>(request); if (response.IsSuccessful) { // Access the deserialized data var smsResult = response.Data; Console.WriteLine($"Transaction ID: {smsResult.SEND_SMS_SUCCESS.TRANSACTION.Id}"); Console.WriteLine($"Valid SMS Sent: {smsResult.SEND_SMS_SUCCESS.VALID_SMS_COUNT}"); Console.WriteLine($"Invalid SMS: {smsResult.SEND_SMS_SUCCESS.INVALID_SMS_COUNT}"); } else { // Handle errors (e.g., HTTP status code, error message) Console.WriteLine($"Request failed: {response.StatusCode} - {response.ErrorMessage}"); }
Scenario 2: Deserialize a Raw XML String
If you already have the XML response as a string (like the one you provided), you can deserialize it directly:
using RestSharp.Serializers.Xml; var xmlResponse = @"<CONTENT> <SEND_SMS_SUCCESS> <TRANSACTION id=""30911386""/> <VALID_SMS_COUNT>2</VALID_SMS_COUNT> <INVALID_SMS_COUNT>0</INVALID_SMS_COUNT> </SEND_SMS_SUCCESS> </CONTENT>"; var serializer = new XmlSerializer(); var result = serializer.Deserialize<CONTENT>(xmlResponse); // Use the result just like in the previous scenario Console.WriteLine($"Transaction ID: {result.SEND_SMS_SUCCESS.TRANSACTION.Id}");
Additional Tips
- Case Sensitivity: XML element/attribute names are case-sensitive, so make sure your POCO property names match exactly (or use
XmlElement/XmlAttributeattributes to map different names). - Namespaces: If your XML includes namespaces, add the
XmlRootandXmlElementattributes with the appropriate namespace values. - Nullable Values: If some elements might be missing from the response, use nullable types (e.g.,
int? VALID_SMS_COUNT) to avoid deserialization errors.
内容的提问来源于stack exchange,提问作者Adem Aygun

