<string xmlns=''> was not expected in c# - c#

Hi all I am trying to serialize value in xml. Every time I am getting <string xmlns=''> was not expected in c# Not able to find root cause plz help me out here.
namespace CustomDataType.usercontrols
{
public partial class CustomDataTypes : System.Web.UI.UserControl, umbraco.editorControls.userControlGrapper.IUsercontrolDataEditor
{
private Status _umbval;
public object value
{
get
{
var status = GetStatus();
return SerializationHelper.ValueToXmlString(status);
}
set
{
//if (value == null || string.IsNullOrEmpty(value.ToString()))
//{
// _umbval = Status.Empty;
//}
//else
//{
_umbval =(Status)SerializationHelper.ValueFromXmlString(value,typeof(Status));
//}
}
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Xml.Serialization;
namespace CustomDataType
{
[Serializable]
[XmlRoot("StatuMain")]
public class Status
{
[XmlElement("statusvalue")]
public string StatusValue { get; set; }
[XmlElement("statusvalue1")]
public string StatusValue1 { get; set; }
[XmlElement("statusvalue2")]
public string StatusValue2 { get; set; }
[XmlElement("statusvalue3")]
public string StatusValue3 { get; set; }
//[XmlElement("isEmailChecked")]
//public bool HasEmailChecked { get; set; }
//[XmlElement("datetime")]
//public DateTime Date { get; set; }
public static Status Empty
{
get
{
var schedule = new Status();
schedule = null;
return schedule;
}
}
}
}

I think you should be using XmlNamespaceManager to set an empty namespace, instead of xmlns..
http://msdn.microsoft.com/en-us/library/d6730bwt(v=vs.80).aspx
XmlNamespaceManager nsmanager = new XmlNamespaceManager(reader.NameTable);
nsmanager.AddNamespace("", "");
YourSeraializationMethod(reader);

Related

How do I call JSON in a simplified manner

I am connecting to an external API which seems to be returning JSON
using (var client = new APIClient())
{
var data = client.General.GetAccountInfo().Data.Balances;
}
When I move over .Data.Balances, it shows:
IEnumerable<API.Net.Objects.Spot.SpotData.APIBalance>
API.Net.Objects.Spot.SpotData.APIAccountInfo.Balances { get; set; }
List of assets and their current balances
Here is an extract of the JSON data:
"balances":[
{
"asset":"ABC",
"free":"0.00000000",
"locked":"0.00000000"
},
{
"asset":"DEF",
"free":"0.00000000",
"locked":"0.00000000"
},
{
"asset":"GHI",
"free":"0.00000000",
"locked":"0.00000000"
}
]
How do I make use of this data so if I type console.writeline(data[0]["asset"]), it gives me ABC?
This seems to be the simplist solution:
using System.Linq;
using (var client = new APIClient())
{
var data = client.General.GetAccountInfo().Data.Balances.ToList();
Console.WriteLine(data[0].asset);
Console.WriteLine(data[0].free);
Console.WriteLine(data[0].locked);
}
Hy,
From the sample file you can create a class ´balance »
Public class balance
{
Public string asset {get; set;}
Public Free .......
Public Locked .....
}
And then you can use Json.net
To deserialize the JSon file
public void serializejson()
{
List balances = JsonConvert.DeserializeObject<List>(data);
}
}
using System;
using System.Collections.Generic;
using System.IO;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace Game
{
public class Balance
{
[JsonPropertyName("asset")]
public string Asset { get; set; }
[JsonPropertyName("free")]
public string Free { get; set; }
[JsonPropertyName("locked")]
public string Locked { get; set; }
}
public class Root
{
[JsonPropertyName("balances")]
public List<Balance> Balances { get; set; }
}
class Program
{
static void Main(string[] args)
{
var data = File.ReadAllText("test.json");
var deserialized = JsonSerializer.Deserialize<Root>(data);
var balances = deserialized.Balances;
// Don't iterati in such a way! Use foreach instead.
for (int i = 0; i < balances.Count; i++)
{
Console.WriteLine($"{balances[i].Asset} {balances[i].Free} {balances[i].Locked}");
}
foreach (var balance in balances)
{
Console.WriteLine($"{balance.Asset} {balance.Free} {balance.Locked}");
}
}
}
}
You can use this code for you:
public class Balance {
public string asset { get; set; }
public string free { get; set; }
public string locked { get; set; }
}
public class Root {
public List<Balance> balances { get; set; }
}
And for deserialize:
using (var client = new APIClient())
{
var data = client.General.GetAccountInfo().Data.Balances;
Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(data);
Console.WriteLine(myDeserializedClass.balances[0].asset);
}

How to Parse XML Where Child Nodes Have The Same Name

I have an XML file that I am parsing through and have come across a specific element that has it's own child nodes. The XML file is below:
<status.AppleSettings>
<AppleInstance MaxCost="250" Status="77" NewMode="5" SharePrice="350"
FlagTF="False" TimeClock="0" TimeClockSec="14"
Options="7532890" ID="JK_7755" Owner="SLP90"
Server="PA.SL90.COL" Name="SLP90" GroupName="COL.PA"
Instance="AppleServiceInstance" NewFlag="True" FinalCount="0"/>
<AppleInstance MaxCost="5" Status="0" NewMode="1" SharePrice="0"
FlagTF="False" TimeClock="300" TimeClockSec="1000"
Options="56794577431" Owner="A.CON" Instance="SL91"
NewFlag="True" FinalCount="1" List="1450, 1430"
Keyrepo="SYSTEMSERVER_7671902"/>
</status.AppleSettings>
As you can see, there's a parent node - AppleSettings and then two child nodes w/ the same name - AppleInstance. I created two separate classes for the child nodes since they have different attributes. I am able to access AppleSettings and when I do a quickwatch I can see the two child nodes inside, I just can't figure out how to access them. New to XML parsing and C# so everything is trial and error, learning a lot from stackoverflow.
Here is the code I have to access the AppleSettings parent node:
private List<Data> GetAppleSettingsNode(List<XmlDocument> XMLdocument, List<Data> DataList)
{
for (int i = 0; i < XMLdocument.Count(); i++)
{
AppleSettings temp = new AppleSettings();
var temp2 = XMLdocument[i].DocumentElement.SelectNodes("//AppleSettings");
foreach (var node in temp2)
{
var temp3 = node.ToString();
}
XmlNode xmlNode1 = XMLdocument[i].SelectSingleNode("//AppleSettings");
XmlSerializer serial1 = new XmlSerializer(typeof(AppleSettings));
temp = (AppleSettings)serial1.Deserialize(new XmlNodeReader(xmlNode1));
}
}
Is it even necessry to access the AppleSettings node? Could I go directly to the two AppleInstance child nodes? If someone could help me out, I'd appreciate it. Thanks!
It is better to use LINQ to XML API.
(1) The code below shows how to access any XML attribute by its name.
(2) .FirstOrDefault()?.Value technique will prevent exceptions generation when an attribute is missing.
c#
void Main()
{
const string FILENAME = #"e:\Temp\AppleSettings.xml";
XDocument doc = XDocument.Load(FILENAME);
foreach (var el in doc.Descendants("AppleInstance"))
{
Console.WriteLine("MaxCost={0}", el.Attributes("MaxCost").FirstOrDefault()?.Value);
Console.WriteLine("Instance={0}", el.Attributes("Instance").FirstOrDefault()?.Value);
Console.WriteLine("GroupName={0}", el.Attributes("GroupName").FirstOrDefault()?.Value);
}
}
Try following :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
namespace ConsoleApplication8
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
XmlReader reader = XmlReader.Create(FILENAME);
XmlSerializer serializer = new XmlSerializer(typeof(Root));
Root root = (Root)serializer.Deserialize(reader);
}
}
public class Root
{
[XmlArray("status.AppleSettings")]
[XmlArrayItem("AppleInstance")]
public List<ApppleInstance> AppleInstances { get; set; }
}
public class ApppleInstance
{
[XmlAttribute()]
public int MaxCost { get; set; }
[XmlAttribute()]
public int Status { get; set; }
[XmlAttribute()]
public int NewMode { get; set; }
[XmlAttribute()]
public int SharePrice { get; set; }
private Boolean _FlagTF { get; set; }
[XmlAttribute()]
public string FlagTF
{
get { return _FlagTF? "True" : "False";}
set { _FlagTF = (value == "True") ? true : false;}
}
[XmlAttribute()]
public int TimeClock { get; set; }
[XmlAttribute()]
public int TimeClockSec { get; set; }
[XmlAttribute()]
public long Options { get; set; }
[XmlAttribute()]
public string ID { get; set; }
[XmlAttribute()]
public string Owner { get; set; }
[XmlAttribute()]
public string Server { get; set; }
[XmlAttribute()]
public string Name { get; set; }
[XmlAttribute()]
public string GroupName { get; set; }
[XmlAttribute()]
public string Instance { get; set; }
private Boolean _NewFlag { get; set; }
[XmlAttribute()]
public string NewFlag
{
get { return _NewFlag ? "True" : "False"; }
set { _NewFlag = (value == "True") ? true : false; }
}
[XmlAttribute()]
public int FinalCount { get; set; }
private int[] _List { get; set; }
[XmlAttribute()]
public string List
{
get { return string.Join(",",_List);}
set { _List = value.Split(new char[] {','}).Select(x => int.Parse(x)).ToArray() ;}
}
[XmlAttribute()]
public string Keyrepo { get; set; }
}
}
The i of LargeXMLResponse[i] is loop count of the Large XML response if your response tag in wrapped up in between, and if you have a alternative way please go ahead with.
var ResponseToList = LargeXMLResponse[i].Descendants("Response").ToList();
if (ResponseToList.Count() > 0){
for (var pf = 0; pf < ResponseToList.Count(); pf++)
{
ResponseInfoList.Add(new ResponseToList{
id = ResponseToList[pf].Descendants("Block").Attributes("id").Count() > 0 ?
ResponseToList[pf].Descendants("Block ").Attributes("id").First().Value : "",
});
}
}

Error when deserializing xml into array

I'm trying to deserialize xml retrieved from a web service call
using (var client = new WebClient())
{
client.UseDefaultCredentials = true;
var content = client.DownloadString("call to service");
System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(List<NewCourseApply.Models.Education>));
using (TextReader textReader = new StringReader(content))
{
var e = (List<NewCourseApply.Models.Education>)serializer.Deserialize(textReader);
}
}
The xml returned from the service is:
<ArrayOfEducation xmlns="http://schemas.datacontract.org/2004/07/CovUni.Domain.Admissions" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"><Education><_auditList xmlns="http://schemas.datacontract.org/2004/07/CovUni.Common.Base" xmlns:a="http://schemas.microsoft.com/2003/10/Serialization/Arrays"/><_apCode>670104552</_apCode><_attendanceType>FT</_attendanceType><_educationId>1</_educationId><_establishmentDetails>test school</_establishmentDetails><_fromDate>2016-11-01T00:00:00</_fromDate><_toDate>2016-11-22T00:00:00</_toDate><_ucasSchoolCode/></Education></ArrayOfEducation>
My client side object is:
[Serializable]
public class Education
{
protected int _apCode;
protected int _educationId;
protected string _establishmentDetails;
protected string _ucasSchoolCode;
protected DateTime? _fromDate;
protected DateTime? _toDate;
protected string _attendanceType;
protected string _auditList;
public int ApCode
{ get { return _apCode;}
set { _apCode = value;} }
public int EducationId
{ get { return _educationId;}
set { _educationId = value;} }
public string EstablishmentDetails
{ get { return _establishmentDetails;}
set { _establishmentDetails = value;} }
public string UcasSchoolCode
{ get { return _ucasSchoolCode;}
set { _ucasSchoolCode = value;} }
public DateTime? FromDate
{ get { return _fromDate;}
set { _fromDate = value;} }
public DateTime? ToDate
{ get { return _toDate;}
set { _toDate = value;} }
public string AttendanceType
{ get { return _attendanceType;}
set { _attendanceType = value;} }
public string AuditList
{ get { return _auditList;}
set { _auditList = value;} }
}
The error I am getting is:
There is an error in XML document (1, 2).
<ArrayOfEducation xmlns='http://schemas.datacontract.org/2004/07/CovUni.Domain.Admissions'> was not expected.
Also if I call a web service call and get the singular Education response i.e.:
<Education xmlns="http://schemas.datacontract.org/2004/07/CovUni.Domain.Admissions" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"><_auditList xmlns="http://schemas.datacontract.org/2004/07/CovUni.Common.Base" xmlns:a="http://schemas.microsoft.com/2003/10/Serialization/Arrays"/><_apCode>670104552</_apCode><_attendanceType>FT</_attendanceType><_educationId>1</_educationId><_establishmentDetails>test school</_establishmentDetails><_fromDate>2016-11-01T00:00:00</_fromDate><_toDate>2016-11-22T00:00:00</_toDate><_ucasSchoolCode/></Education>
Surely I just need one Simple Education class on the client side that can deserialise from the 2 examples of xml i have provided i.e. array and non array
Can some of you kind souls let me know where i'm going wrong or if there's a better way of doing this?
Many Thanks
Change the Class to
[XmlRoot("ArrayOfEducation", Namespace = "http://schemas.datacontract.org/2004/07/CovUni.Domain.Admissions")]
public class ArrayOfEducation
{
[XmlElement("Education")]
public List<ContainerEducation> education { get; set; }
}
public class ContainerEducation
{
[XmlElement(ElementName = "_apCode")]
public int _apCode { get; set; }
[XmlElement(ElementName = "_educationId")]
public int _educationId { get; set; }
[XmlElement(ElementName = "_establishmentDetails")]
public string _establishmentDetails { get; set; }
[XmlElement(ElementName = "_ucasSchoolCode")]
public string _ucasSchoolCode { get; set; }
[XmlElement(ElementName = "_fromDate")]
public DateTime? _fromDate { get; set; }
[XmlElement(ElementName = "_toDate")]
public DateTime? _toDate { get; set; }
[XmlElement(ElementName = "_attendanceType")]
public string _attendanceType { get; set; }
[XmlElement(ElementName = "_auditList", Namespace = "http://schemas.datacontract.org/2004/07/CovUni.Common.Base")]
public string _auditList { get; set; }
}
And Deserialize below way. Now, when I run the code to deserialize your XML, I do get the objects filled nicely.
XmlSerializer mySerializer = new XmlSerializer(typeof(ArrayOfEducation));
using (TextReader textReader = new StringReader(content))
{
ArrayOfEducation arrEdu = (ArrayOfEducation)mySerializer.Deserialize(textReader);
}
Update as per your comment:
If you are sure that web service is going to send single Education then you need to change the class to
[XmlRoot("ArrayOfEducation", Namespace = "http://schemas.datacontract.org/2004/07/CovUni.Domain.Admissions")]
public class ArrayOfEducation
{
[XmlElement("Education")]
public ContainerEducation education { get; set; }
}

Using Linq to sql for windows phone

I am trying to show out History for my windows 8 application which includes date, time , Floor ,Zone , Longitutde and latitude. I tried the code below but there was no output in it above.
THe image you can see on the link down below that I want to show on my application.But I can see nothing when I run my program.
I have three classes for using linq to sql to retrieve database and show information through it.The main class is History.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using System.IO.IsolatedStorage;
using System.Data.Linq;
using System.Data.Linq.Mapping;
using System.ComponentModel;
using System.Collections.ObjectModel;
using System.Text;
using System.Data.Linq;
namespace SmartParking
{
public partial class History : PhoneApplicationPage
{
private readonly HistoryDataContext historylog;
public History()
{
InitializeComponent();
// createDB();
}
public HistoryDataContext Log
{
get { return historylog; }
}
public void createDB()
{
using (HistoryDataContext historylog = new HistoryDataContext(HistoryDataContext.DBConnectionString))
{
if (historylog.DatabaseExists() == false)
{
historylog.CreateDatabase();
addDataDB();
}
}
}
public void addDataDB()
{
using (HistoryDataContext historylog = new HistoryDataContext(HistoryDataContext.DBConnectionString))
{
HistoryDB hdb = new HistoryDB
{
// Date = DateTime.Today,
// Time = DateTime.Now.TimeOfDay,
Zone = Checkin.Zone_st,
Floor = Checkin.Floor_st,
location_latitude = Checkin.Latitud_do,
location_longtitud = Checkin.Longtitude_do
};
historylog.history.InsertOnSubmit(hdb);
historylog.SubmitChanges();
GetHistoryLog();
}
}
public IList<HistoryDB> GetHistoryLog()
{
IList<HistoryDB> HistoryList = null;
using (HistoryDataContext historylog = new HistoryDataContext(HistoryDataContext.DBConnectionString))
{
IQueryable<HistoryDB> query = from histoy in historylog.history select histoy;
HistoryList = query.ToList();
}
return HistoryList ;
}
}
}
The next class is HistoryDB.cs with the tables and columns
[Table]
public class HistoryDB
{
[Column(CanBeNull = false)]
public DateTime Date
{ get; set; }
[Column(CanBeNull = false)]
public TimeSpan Time
{ get; set; }
[Column(CanBeNull = false)]
public String Zone
{ get; set; }
[Column(CanBeNull = false)]
public String Floor
{ get; set; }
[Column(CanBeNull = false)]
public double location_latitude
{ get; set; }
[Column(CanBeNull = false)]
public double location_longtitud
{ get; set; }
}
The next class is HistoryDataContext.cs.
public class HistoryDataContext:DataContext
{
public static string DBConnectionString = "Data Source=isostore:/History.sdf";
public HistoryDataContext(string DBConnectionString)
: base(DBConnectionString)
{
}
public Table<HistoryDB> history
{
get
{
return this.GetTable<HistoryDB>();
}
}
}
What I am trying is to get information from the NFC tag and store it in the local database and then retrieve it in the history page. The code below is to read from nfc tag but I dunno how again to save in the local databse from there and retrive it back in the history page.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Networking.Proximity;
using NdefLibrary.Ndef;
using NdefLibraryWp.Ndef;
using Windows.Networking.Sockets; // needed for DataReader, DataWriter
using Windows.UI.Popups;
using Microsoft.Phone.UserData;
using System.Text;
using Windows.Phone.PersonalInformation;
using SmartParking.Resources;
using System.Diagnostics;
namespace SmartParking
{
public partial class Checkin : PhoneApplicationPage
{
private ProximityDevice _device;
private long _subscriptionIdNdef;
public static double Latitud_do { get; set; }
public static double Longtitude_do { get; set; }
public static string Floor_st { get; set; }
public static string Zone_st { get; set; }
History store = new History();
public Checkin()
{
InitializeProximityDevice();
InitializeComponent();
}
private void SetLogStatus(string newStatus)
{
Dispatcher.BeginInvoke(() => { if (LogStatus != null) LogStatus.Text = newStatus; });
}
private void SetFloorStatus(string newStatus)
{
Dispatcher.BeginInvoke(() => { if (FloorStatus != null) FloorStatus.Text = newStatus; });
}
private void ApplicationBarIconButton_Click(object sender, System.EventArgs e)
{
MessageBox.Show(" ");
}
private void InitializeProximityDevice()
{
_device = Windows.Networking.Proximity.ProximityDevice.GetDefault();
if (_device != null)
{
_subscriptionIdNdef = _device.SubscribeForMessage("NDEF", MessageReceivedHandler);
}
}
private void MessageReceivedHandler(ProximityDevice sender, ProximityMessage message)
{
var rawMsg = message.Data.ToArray();
var ndefMessage = NdefMessage.FromByteArray(rawMsg);
////// Loop over all records contained in the NDEF message
foreach (NdefRecord record in ndefMessage)
{
if (NdefTextRecord.IsRecordType(record))
{
// Convert and extract URI info
var textRecord = new NdefTextRecord(record);
//var str = textRecord.Text;
string[] str = textRecord.Text.Split('|');
var latitude = str[2];
Latitud_do = double.Parse(latitude);
var longtitude = str[3];
Longtitude_do = double.Parse(longtitude);
var Floor_st = str[0];
var Zone_st = str[1];
SetLogStatus("Floor: " + Floor_st + " Zone: " + Zone_st );
SetFloorStatus("Longitude: " + latitude + " Longitude: " + longtitude);
store.addDataDB();
}
}
}
}
}
The Image of the table is in the link below
https://www.dropbox.com/s/g87yta6hegjstge/Untitled.png?dl=0
try this:
In Database There Should be a Primary key otherwise it would Throw an Exception and the Datatype that is TimeSpan not supported so you need to take DateTime or String as Done Below :
[Table]
public class HistoryDB
{
[Column(IsPrimaryKey = true)]
public int Id { get; set; }
[Column(CanBeNull = false)]
public DateTime Date
{ get; set; }
[Column(CanBeNull = false)]
public DateTime Time
{ get; set; }
[Column(CanBeNull = false)]
public String Zone
{ get; set; }
[Column(CanBeNull = false)]
public String Floor
{ get; set; }
[Column(CanBeNull = false)]
public double location_latitude
{ get; set; }
[Column(CanBeNull = false)]
public double location_longtitud
{ get; set; }
}
public void addDataDB()
{
using (HistoryDataContext historylog = new HistoryDataContext(HistoryDataContext.DBConnectionString))
{
HistoryDB hdb = new HistoryDB
{
Id = 0,
Date = DateTime.Today,
Time = DateTime.Now,
Zone = "Zone",
Floor = "Floore",
location_latitude = 00.00,
location_longtitud = 00.00
};
historylog.history.InsertOnSubmit(hdb);
historylog.SubmitChanges();
GetHistoryLog();
}
}
I have implemented above thing and its working Properly

Problem with XML Deserialization C#

I am having trouble with XML deserialization.
In a nutshell -
I have 2 classes:
SMSMessage
SMSSendingResponse
I call an API that takes a bunch of parameters (represented by SMSMessage class)
It returns an XML response.
The response looks like this:
<?xml version="1.0" encoding="utf-8"?>
<data>
<status>1</status>
<message>OK</message>
<results>
<result>
<account>12345</account>
<to>012345678</to>
<from>054321</from>
<message>Testing</message>
<flash></flash>
<replace></replace>
<report></report>
<concat></concat>
<id>f8d3eea1cbf6771a4bb02af3fb15253e</id>
</result>
</results>
</data>
Here is the SMSMessage class (with the xml serialization attributes so far)
using System.Xml.Serialization;
namespace XMLSerializationHelp
{
[XmlRoot("results")]
public class SMSMessage
{
public string To
{
get
{
return Result.To;
}
}
public string From
{
get
{
return Result.From;
}
}
public string Message
{
get
{
return Result.Message;
}
}
[XmlElement("result")]
public Result Result { get; set; }
}
}
Here is SMSMessageSendingResponse:
using System.Xml.Serialization;
namespace XMLSerializationHelp
{
[XmlRoot("data")]
public class SMSSendingResponse
{
//should come from the results/result/account element. in our example "12345"
public string AccountNumber
{
get
{
return SMSMessage.Result.AccountNumber;
}
}
//should come from the "status" xml element
[XmlElement("status")]
public string Status { get; set; }
//should come from the "message" xml element (in our example - "OK")
[XmlElement("message")]
public string Message { get; set; }
//should come from the "id" xml element (in our example - "f8d3eea1cbf6771a4bb02af3fb15253e")
public string ResponseID
{
get
{
return SMSMessage.Result.ResponseID;
}
}
//should be created from the results/result element - ignore flash, replace, report and concat elements for now.
[XmlElement("results")]
public SMSMessage SMSMessage { get; set; }
}
}
Here is the other class (Result) - I want to get rid of this, so only the 2 previously mentioned classes remain
using System.Xml.Serialization;
namespace XMLSerializationHelp
{
[XmlRoot("result")]
public class Result
{
[XmlElement("account")]
public string AccountNumber{ get; set; }
[XmlElement("to")]
public string To { get; set; }
[XmlElement("from")]
public string From { get; set; }
[XmlElement("message")]
public string Message { get; set; }
[XmlElement("id")]
public string ResponseID { get; set; }
}
}
I don't want SMSMessage to be aware of the SMSSendingResponse - as this will be handled by a different part of my application
I hope this helps. The XML structure implies the <result> element can occur more than once, so see if this helps you achieve what you need:
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Xml;
namespace XMLSerializationHelp
{
class Program
{
static void Main(string[] args)
{
string strXML = #"<?xml version=""1.0"" encoding=""utf-8""?>
<data>
<status>1</status>
<message>OK</message>
<results>
<result>
<account>12345</account>
<to>012345678</to>
<from>054321</from>
<message>Testing</message>
<flash></flash>
<replace></replace>
<report></report>
<concat></concat>
<id>f8d3eea1cbf6771a4bb02af3fb15253e</id>
</result>
</results>
</data>";
XmlSerializer serializer = new XmlSerializer(typeof(SMSSendingResponse));
SMSSendingResponse obj = (SMSSendingResponse)serializer.Deserialize(new XmlTextReader(strXML, XmlNodeType.Document, null));
Console.WriteLine("Status: {0}", obj.Status);
Console.WriteLine("Message: {0}", obj.Message);
Console.WriteLine("Account Number: {0}", obj.AccountNumber);
Console.WriteLine("ResponseID: {0}", obj.ResponseID);
Console.WriteLine("To: {0}", obj.To);
Console.WriteLine("From: {0}", obj.From);
Console.WriteLine("ResultMessage: {0}", obj.ResultMessage);
Console.ReadLine();
}
}
[Serializable]
[XmlRoot("data")]
public class SMSSendingResponse
{
public SMSSendingResponse() {}
//should come from the "status" xml element
[XmlElement("status")]
public string Status { get; set; }
//should come from the "message" xml element (in our example - "OK")
[XmlElement("message")]
public string Message { get; set; }
//should come from the results/result/account element. in our example "12345"
[XmlIgnore()]
public string AccountNumber
{
get
{
Result r = FirstResult;
return (r != null) ? r.AccountNumber : null;
}
}
//should come from the "id" xml element (in our example - "f8d3eea1cbf6771a4bb02af3fb15253e")
[XmlIgnore()]
public string ResponseID
{
get
{
Result r = FirstResult;
return (r != null) ? r.ResponseID : null;
}
}
[XmlIgnore()]
public string To
{
get
{
Result r = FirstResult;
return (r != null) ? r.To : null;
}
}
[XmlIgnore()]
public string From
{
get
{
Result r = FirstResult;
return (r != null) ? r.From : null;
}
}
[XmlIgnore()]
public string ResultMessage
{
get
{
Result r = FirstResult;
return (r != null) ? r.Message : null;
}
}
[XmlArray("results"), XmlArrayItem("result", typeof(Result))]
public List<Result> Results
{
get { return (_Results); }
set { _Results = value; }
} private List<Result> _Results = new List<Result>();
[XmlIgnore()]
public Result FirstResult
{
get
{
return (_Results != null && _Results.Count > 0) ? _Results[0] : null;
}
}
}
[XmlType(TypeName = "result"), Serializable]
public class Result
{
public Result() {}
[XmlElement("account")]
public string AccountNumber { get; set; }
[XmlElement("to")]
public string To { get; set; }
[XmlElement("from")]
public string From { get; set; }
[XmlElement("message")]
public string Message { get; set; }
[XmlElement("id")]
public string ResponseID { get; set; }
}
}

Categories

Resources