XmlSerializer not correct format result - c#

The output i want as below
<SOAP:Envelope xmlns:SOAP='http://schemas.xmlsoap.org/soap/envelope/' >
<SOAP:Body UserGUID = '{redacted}' >
<m:SaveOrder xmlns:m = 'http://www.e-courier.com/schemas/' >
<Order UserID = '1' Notes = 'Signature Requiered' CustomerID = '3' >
</Order >
</m:SaveOrder >
</SOAP:Body >
</SOAP:Envelope >
The output xml that i am getting as my result
<?xml version="1.0"?>
<SOAP:Envelope xmlns:m="http://www.e-courier.com/schemas/" xmlns:SOAP="http://schemas.xmlsoap.org/soap/envelope/">
<SOAP:Body UserGUID="">
<m:SaveOrder >
<m:Order UserID="" Notes="" CustomerID="" />
</m:SaveOrder>
</SOAP:Body>
</SOAP:Envelope>
My XML Class code:
[XmlRoot(ElementName="Order")]
public class Order {
[XmlAttribute(AttributeName="UserID")]
public string UserID { get; set; }
[XmlAttribute(AttributeName="Notes")]
public string Notes { get; set; }
[XmlAttribute(AttributeName="CustomerID")]
public string CustomerID { get; set; }
}
[XmlRoot(ElementName="SaveOrder", Namespace="http://www.e-courier.com/schemas/")]
public class SaveOrder {
[XmlElement(ElementName="Order")]
public Order Order { get; set; }
[XmlAttribute(AttributeName="m", Namespace="http://www.w3.org/2000/xmlns/")]
public string M { get; set; }
}
[XmlRoot(ElementName="Body", Namespace="http://schemas.xmlsoap.org/soap/envelope/")]
public class Body {
[XmlElement(ElementName="SaveOrder", Namespace="http://www.e-courier.com/schemas/")]
public SaveOrder SaveOrder { get; set; }
[XmlAttribute(AttributeName="UserGUID")]
public string UserGUID { get; set; }
}
[XmlRoot(ElementName="Envelope", Namespace="http://schemas.xmlsoap.org/soap/envelope/")]
public class Envelope {
[XmlElement(ElementName="Body", Namespace="http://schemas.xmlsoap.org/soap/envelope/")]
public Body Body { get; set; }
[XmlAttribute(AttributeName="SOAP", Namespace="http://www.w3.org/2000/xmlns/")]
public string SOAP { get; set; }
}
My Code where i am generating xml
var SaveOrder = new ECSaveOrderRequest.Envelope
{
Body = new ECSaveOrderRequest.Body
{
UserGUID = guid,
SaveOrder = new ECSaveOrderRequest.SaveOrder
{
Order = new ECSaveOrderRequest.Order
{
UserID = Uid,
Notes = "",
CustomerID=""
}
}
}
};
var ns = new XmlSerializerNamespaces();
ns.Add("SOAP", "http://schemas.xmlsoap.org/soap/envelope/");
ns.Add("m", "http://www.e-courier.com/schemas/");
var ser = new XmlSerializer(typeof(ECSaveOrderRequest.Envelope));
using (var ms = new MemoryStream())
{
// write the DTO to the MemoryStream
ser.Serialize(ms, SaveOrder, ns);
using (var wc = new WebClient())
{
wc.Encoding = System.Text.Encoding.UTF8;
ms.Position = 0;
StreamReader stream = new StreamReader(ms);
string requestString = stream.ReadToEnd();
var resp = wc.UploadData(ECUrl, ms.ToArray());
}
}

You need to explicitly clear the xml namespace on SaveOrder.Order or the serializer will default to SaveOrder's xml namespace.
Here you go:
using System;
using System.IO;
using System.Text;
using System.Xml.Serialization;
namespace ECSaveOrderRequest
{
/*
* <SOAP:Envelope xmlns:SOAP='http://schemas.xmlsoap.org/soap/envelope/' >
<SOAP:Body UserGUID = '{redacted}' >
<m:SaveOrder xmlns:m = 'http://www.e-courier.com/schemas/' >
<Order UserID = '1' Notes = 'Signature Requiered' CustomerID = '3' >
</Order >
</m:SaveOrder >
</SOAP:Body >
</SOAP:Envelope >*/
public class Order
{
[XmlAttribute(AttributeName = "UserID")]
public string UserID { get; set; }
[XmlAttribute(AttributeName = "Notes")]
public string Notes { get; set; }
[XmlAttribute(AttributeName = "CustomerID")]
public string CustomerID { get; set; }
}
public class SaveOrder
{
[XmlElement(ElementName = "Order", Namespace = "")]
public Order Order { get; set; }
}
public class Body
{
[XmlElement(ElementName = "SaveOrder", Namespace = "http://www.e-courier.com/schemas/")]
public SaveOrder SaveOrder { get; set; }
[XmlAttribute(AttributeName = "UserGUID")]
public string UserGUID { get; set; }
}
[XmlRoot(ElementName = "Envelope", Namespace = "http://schemas.xmlsoap.org/soap/envelope/")]
public class Envelope
{
[XmlElement(ElementName = "Body", Namespace = "http://schemas.xmlsoap.org/soap/envelope/")]
public Body Body { get; set; }
[XmlAttribute(AttributeName = "SOAP", Namespace = "http://www.w3.org/2000/xmlns/")]
public string SOAP { get; set; }
}
class Program
{
static void Main(string[] args)
{
var SaveOrder = new ECSaveOrderRequest.Envelope
{
Body = new ECSaveOrderRequest.Body
{
UserGUID = "{redacted}",
SaveOrder = new ECSaveOrderRequest.SaveOrder
{
Order = new ECSaveOrderRequest.Order
{
UserID = "1",
Notes = "Signature Requiered",
CustomerID = "3"
}
}
}
};
var ns = new XmlSerializerNamespaces();
ns.Add("SOAP", "http://schemas.xmlsoap.org/soap/envelope/");
ns.Add("m", "http://www.e-courier.com/schemas/");
var ser = new XmlSerializer(typeof(ECSaveOrderRequest.Envelope));
var ms = new MemoryStream();
// write the DTO to the MemoryStream
ser.Serialize(ms, SaveOrder, ns);
ms.Position = 0;
var xml = Encoding.UTF8.GetString(ms.GetBuffer());
Console.WriteLine(xml);
Console.ReadKey();
}
}
}
outputs
<?xml version="1.0"?>
<SOAP:Envelope xmlns:m="http://www.e-courier.com/schemas/" xmlns:SOAP="http://schemas.xmlsoap.org/soap/envelope/">
<SOAP:Body UserGUID="{redacted}">
<m:SaveOrder>
<Order UserID="1" Notes="Signature Requiered" CustomerID="3" />
</m:SaveOrder>
</SOAP:Body>
</SOAP:Envelope>
Which is a serialization of the same XML document as
<SOAP:Envelope xmlns:SOAP='http://schemas.xmlsoap.org/soap/envelope/' >
<SOAP:Body UserGUID = '{redacted}' >
<m:SaveOrder xmlns:m = 'http://www.e-courier.com/schemas/' >
<Order UserID = '1' Notes = 'Signature Requiered' CustomerID = '3' >
</Order >
</m:SaveOrder >
</SOAP:Body>
</SOAP:Envelope>
.

Related

How to deserialize this xml to objects?

I'm fetching data in the format of this:
<ReplyUserAccount xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" requestid="" version="1.0" xmlns="url">
<Sender partnerid="xx">xx</Sender>
<Users>
<User method="GET" ResultCode="OK" Description="">
<Guid>xx</Guid>
<FirstName>xx</FirstName>
<LastName>xx</LastName>
<Phone>xx</Phone>
<Mobile>xx</Mobile>
<Email>xx</Email>
<EmplNo>xx</EmplNo>
<TacPermission />
<InvPermission>xx</InvPermission>
<CustomerId>xx</CustomerId>
</User>
</Users>
</ReplyUserAccount>
With the following C# objects:
[XmlRoot("ReplyUserAccount")]
public class ReplyUserAccount
{
[XmlElement("Users")]
public Users Users{ get; set; }
}
[XmlType("Users")]
public class Users
{
[XmlElement("User")]
public List<User> UserList{ get; set; }
}
[XmlType("User")]
public class User
{
[XmlElement("EmplNo")]
public string Id{ get; set; }
[XmlElement("Guid")]
public string Guid { get; set; } = null;
[XmlElement("Email")]
public string Email { get; set; }
[XmlElement("FirstName")]
public string FirstName { get; set; }
[XmlElement("LastName")]
public string LastName { get; set; }
public bool Active { get; set; } = true;
public string PhoneNumber { get; set; } = null;
}
And the following deserializing:
var result = await httpClient.GetAsync(url);
var xdoc = XDocument.Parse(await result.Content.ReadAsStringAsync());
XmlSerializer serializer = new XmlSerializer(typeof(ReplyUserAccount));
var content = xdoc.ToString();
TextReader reader = new StringReader(content);
var res = (ReplyUserAccount)serializer.Deserialize(reader);
But I get the following error:
InvalidOperationException: <ReplyUserAccount xmlns='xxx'> was not expected.
I'm a little bit lost as to how to properly deserialize this specific xml data. Any and all help with regards to this is greatly appreciated.
To fix the error, You have to remove xmlns and xsi in xml text before deserialize. You can remove xmlns and xsi like this:
var content = xdoc.ToString();
string strXMLPattern = #"xmlns(:\w+)?=""([^""]+)""|xsi(:\w+)?=""([^""]+)""";
content = Regex.Replace(content, strXMLPattern, "");
Therefore the method should be as follows
var result = await httpClient.GetAsync(url);
var xdoc = XDocument.Parse(await result.Content.ReadAsStringAsync());
XmlSerializer serializer = new XmlSerializer(typeof(ReplyUserAccount));
var content = xdoc.ToString();
string strXMLPattern = #"xmlns(:\w+)?=""([^""]+)""|xsi(:\w+)?=""([^""]+)""";
content = Regex.Replace(content, strXMLPattern, "");
TextReader reader = new StringReader(content);
var res = (ReplyUserAccount)serializer.Deserialize(reader);

C# Code that Parses the Response from Restful Webservice

I have a webservice that reads the response. It can't parse the response data, because the emsg is null.
Below is the restful webservice, connected to it, and the data returned.
if (response.Body != null && response.Body != "null")
{
var xDocument = XDocument.Parse(response.Body);
var emsg = xDocument.Element("T_OUTPUT").LastNode;
if (emsg != null)
{
var parsedData =
(
from e in xDocument.Element("items").Descendants()
select new ProductPipelineTankInventoryEntity
{
BUKRS = (long)e.Element("BUKRS"),
WERKS = (long)e.Element("WERKS"),
NAME1 = e.Element("NAME1").ToString(),
REGIO = e.Element("REGIO").ToString(),
MATKL = e.Element("MATKL").ToString(),
MATNR = (long)e.Element("MATNR"),
LGORT = e.Element("LGORT").ToString(),
GRDIP = (double)e.Element("GRDIP"),
TRNDATE = DateTime.Parse(e.Element("TRNDATE").ToString()),
VOL_NATURAL = (double)e.Element("VOL_NATURAL"),
GRDIP_RUN = (double)e.Element("GRDIP_RUN"),
VOL_RUNNING = (double)e.Element("VOL_RUNNING")
}
).ToList();
ret.AddRange(parsedData);
}
}
<ns0:YV_PIPELINE_PLANT_DIP_DETAILS.Response xmlns:ns0="urn:sap-com:document:sap:rfc:functions">
<E_MSG/>
<T_OUTPUT>
<item>
<BUKRS>2200</BUKRS>
<WERKS>2222</WERKS>
<NAME1>IOCL,JHARSUGUDA TERMINAL</NAME1>
<REGIO>OR</REGIO>
<MATKL>BULK-MS</MATKL>
<MATNR>16400</MATNR>
<LGORT>T005</LGORT>
<GRDIP>1005.5</GRDIP>
<TRNDATE>2019-08-05</TRNDATE>
<VOL_NATURAL>2048.080</VOL_NATURAL>
<GRDIP_RUN>0825.5</GRDIP_RUN>
<VOL_RUNNING>1686.155</VOL_RUNNING>
</item>
<item>
<BUKRS>2200</BUKRS>
<WERKS>2222</WERKS>
<NAME1>IOCL,JHARSUGUDA TERMINAL</NAME1>
<REGIO>OR</REGIO>
<MATKL>BULK-MS</MATKL>
<MATNR>16400</MATNR>
<LGORT>T006</LGORT>
<GRDIP>173.9</GRDIP>
<TRNDATE>2019-08-05</TRNDATE>
<VOL_NATURAL>776.741</VOL_NATURAL>
<GRDIP_RUN>0915.9</GRDIP_RUN>
<VOL_RUNNING>4130.508</VOL_RUNNING>
</item>
</T_OUTPUT>
</ns0:YV_PIPELINE_PLANT_DIP_DETAILS.Response>
The above code I tried. Below part is of the response output.
You need to have namespaces and change from "items" to "item". For test I read xml from a file instead of a response.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.IO;
using System.Globalization;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
string xmlResponse = File.ReadAllText(FILENAME);
XDocument xDocument = XDocument.Parse(xmlResponse);
XElement emsg = xDocument.Descendants().Where(x => x.Name.LocalName == "T_OUTPUT").FirstOrDefault();
XNamespace ns = emsg.GetDefaultNamespace();
if (emsg != null)
{
var parsedData =
(
from e in xDocument.Descendants(ns + "item")
select new ProductPipelineTankInventoryEntity
{
BUKRS = (long)e.Element(ns + "BUKRS"),
WERKS = (long)e.Element(ns + "WERKS"),
NAME1 = (string)e.Element(ns + "NAME1"),
REGIO = (string)e.Element(ns + "REGIO"),
MATKL = (string)e.Element(ns + "MATKL"),
MATNR = (long)e.Element(ns + "MATNR"),
LGORT = (string)e.Element(ns + "LGORT"),
GRDIP = (double)e.Element(ns + "GRDIP"),
TRNDATE = (DateTime)e.Element(ns + "TRNDATE"),
VOL_NATURAL = (double)e.Element(ns + "VOL_NATURAL"),
GRDIP_RUN = (double)e.Element(ns + "GRDIP_RUN"),
VOL_RUNNING = (double)e.Element(ns + "VOL_RUNNING")
}
).ToList();
}
}
}
public class ProductPipelineTankInventoryEntity
{
public long BUKRS { get; set; }
public long WERKS { get; set; }
public string NAME1 { get; set; }
public string REGIO { get; set; }
public string MATKL { get; set; }
public long MATNR { get; set; }
public string LGORT { get; set; }
public double GRDIP { get; set; }
public DateTime TRNDATE { get; set; }
public double VOL_NATURAL { get; set; }
public double GRDIP_RUN { get; set; }
public double VOL_RUNNING { get; set; }
}
}

Formatting issue with a class generated xml in ASP.Net C#

My below my code which generate an xml and return the generated xml but the current format is not the structure expected:
My Class:
public class response
{
[StringLength(64)]
public string reference { get; set; }
public int responseCode { get; set; }
[StringLength(140)]
public string responseMessage { get; set; }
[StringLength(32)]
public string transactionId { get; set; }
public List<account> accounts { get; set; }
}
public class account
{
[StringLength(64)]
public string account_number { get; set; }
}
rs = "<?xml version='1.0' encoding='UTF-8'?><USSDResponse><Status>true</Status><StatusMessage>Account details returned for 08069262257</StatusMessage><SessionID>31853F5C-A1C1-2A6F-E054-8E1F65C33B15</SessionID><AccountNumber><AccountNo>0003893369</AccountNo><AccountStatus>ACCOUNT OPEN REGULAR</AccountStatus><AvailableBalance>17674.69</AvailableBalance><AccountName>IYEKE IKECHUKWU I.</AccountName><AccountCurrency>NGN</AccountCurrency><ProductName>CURRENT STAFF</ProductName></AccountNumber><AccountNumber><AccountNo>0064612613</AccountNo><AccountStatus>ACCOUNT OPEN REGULAR</AccountStatus><AvailableBalance>201132.18</AvailableBalance><AccountName>IKECHUKWU ISRAEL IYEKE</AccountName><AccountCurrency>NGN</AccountCurrency><ProductName>HIDA</ProductName></AccountNumber></USSDResponse>";
x.LoadXml(rs);
status = x.GetElementsByTagName("Status")[0].InnerText;
SessionID = x.GetElementsByTagName("SessionID")[0].InnerText;
if (status != null && status == "true")
{
var accts = x.GetElementsByTagName("AccountNo");
var names = x.GetElementsByTagName("ProductName");
if (accts.Count >= 2)
{
//var AcctNo = new accounts();
foreach (XmlElement a in accts)
{
var acctNo = a.InnerText.Substring(0, 10);
accounts.Add(new account { account_number = acctNo });
}
o.accounts = accounts;
o.reference = reference;
o.responseCode = 6;
o.responseMessage = "Please you can only purchase airtime in naira only and no kobo inclusive.";
o.transactionId = "Nil";
logger.Info($"Wrong amount: {amountString} including kobo entered by the user for mobile number: {msisdn}");
return o;
}
}
Result:
<response xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<reference>565695769-8490890112091</reference>
<responseCode>6</responseCode>
<responseMessage>Please you can only purchase airtime in naira only and no kobo inclusive.</responseMessage>
<transactionId>Nil</transactionId>
<accounts>
<account><account_number>0003893369</account_number></account>
<account><account_number>0064612613</account_number></account>
</accounts>
</response>
My above code generate an xml and return the generated xml but the current format is not the structure expected:But I want the result to be exactly with the removal of tag <account_number></account_number>:
<response xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<reference>565695769-8490890112091</reference>
<responseCode>6</responseCode>
<responseMessage>Please you can only purchase airtime in naira only and no kobo inclusive.</responseMessage>
<transactionId>Nil</transactionId>
<accounts>
<account>0003893369</account>
<account>0064612613</account>
</accounts>
</response>
Modify your class structure as below,
public class Accounts {
public Accounts ()
{
Account = new List<string>();
}
public List<string> Account { get; set; }
}
public class Response {
...
public Accounts Accounts { get; set; }
}

Get text for xml node

Sample XML:
<query yahoo:count="1" yahoo:created="2016-03-31T06:43:49Z" yahoo:lang="en-US">
<results>
<channel>
<item>
<yweather:condition code="28" date="Thu, 31 Mar 2016 08:00 AM SAST" temp="58" text="Mostly Cloudy"/>
</item>
</channel>
</results>
</query>
Code:
string weburl = "https://query.yahooapis.com/v1/public/yql?q=select%20item.condition%20from%20weather.forecast%20where%20woeid%20in%20%28select%20woeid%20from%20geo.places%281%29%20where%20text%3D%22Cape%20Town%22%29&format=xml&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys";
var xml = await new WebClient().DownloadStringTaskAsync(new Uri(weburl));
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
XmlElement root = doc.DocumentElement;
XmlNodeList nodes = root.SelectNodes("//query/results/channel/item");
foreach (XmlNode node in nodes)
{
MessageBox.Show(node.InnerXml);
}
I have been struggling to just get the temp and text outputed but I can't find way how to, this is as far as I got.
You can access XML attributes from XmlNode.Attributes property :
var condition = doc.SelectSingleNode("/query/results/channel/item/*");
MessageBox.Show(condition.Attributes["text"].Value);
MessageBox.Show(condition.Attributes["temp"].Value);
Try this....
Usings....
using System.IO;
using System.Net;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
Classes....
[XmlRoot(ElementName = "condition", Namespace = "http://xml.weather.yahoo.com/ns/rss/1.0")]
public class Condition
{
[XmlAttribute(AttributeName = "yweather", Namespace = "http://www.w3.org/2000/xmlns/")]
public string Yweather { get; set; }
[XmlAttribute(AttributeName = "code")]
public string Code { get; set; }
[XmlAttribute(AttributeName = "date")]
public string Date { get; set; }
[XmlAttribute(AttributeName = "temp")]
public string Temp { get; set; }
[XmlAttribute(AttributeName = "text")]
public string Text { get; set; }
}
[XmlRoot(ElementName = "item")]
public class Item
{
[XmlElement(ElementName = "condition", Namespace = "http://xml.weather.yahoo.com/ns/rss/1.0")]
public Condition Condition { get; set; }
}
[XmlRoot(ElementName = "channel")]
public class Channel
{
[XmlElement(ElementName = "item")]
public Item Item { get; set; }
}
[XmlRoot(ElementName = "results")]
public class Results
{
[XmlElement(ElementName = "channel")]
public Channel Channel { get; set; }
}
[XmlRoot(ElementName = "query")]
public class Query
{
[XmlElement(ElementName = "results")]
public Results Results { get; set; }
[XmlAttribute(AttributeName = "yahoo", Namespace = "http://www.w3.org/2000/xmlns/")]
public string Yahoo { get; set; }
[XmlAttribute(AttributeName = "count", Namespace = "http://www.yahooapis.com/v1/base.rng")]
public string Count { get; set; }
[XmlAttribute(AttributeName = "created", Namespace = "http://www.yahooapis.com/v1/base.rng")]
public string Created { get; set; }
[XmlAttribute(AttributeName = "lang", Namespace = "http://www.yahooapis.com/v1/base.rng")]
public string Lang { get; set; }
}
Code...
XmlDocument xmlDocument = new XmlDocument();
try
{
xmlDocument.Load("https://query.yahooapis.com/v1/public/yql?q=select%20item.condition%20from%20weather.forecast%20where%20woeid%20in%20%28select%20woeid%20from%20geo.places%281%29%20where%20text%3D%22Cape%20Town%22%29&format=xml&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys");
string XMLxmlDocument = xmlDocument.InnerXml.ToString();
byte[] BUFXML = ASCIIEncoding.UTF8.GetBytes(XMLxmlDocument);
MemoryStream ms1 = new MemoryStream(BUFXML);
XmlSerializer DeserializerPlaces = new XmlSerializer(typeof(Query));//, new XmlRootAttribute("Query"));
using (XmlReader reader = new XmlTextReader(ms1))
{
Query dezerializedXML = (Query)DeserializerPlaces.Deserialize(reader);
string temp = dezerializedXML.Results.Channel.Item.Condition.Temp;
string text = dezerializedXML.Results.Channel.Item.Condition.Text;
}// Put a break-point here, then mouse-over temp and text, you should have you values (dezerializedXML contains the entire object)
}
catch (System.Exception)
{
throw;
}
I used xml linq along with Regex. I had to fix issues with your xml. I think the main issue was the namespaces.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.Text.RegularExpressions;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string xml =
"<?xml version=\"1.0\" encoding=\"utf-8\" ?>" +
"<Root xmlns:yahoo=\"abc\" xmlns:yweather=\"def\">" +
"<query yahoo:count=\"1\" yahoo:created=\"2016-03-31T06:43:49Z\">" +
"yahoo:lang=\"en-US\"><results>" +
"<channel>" +
"<item>" +
"<yweather:condition>" +
"code=\"28\" date=\"Thu, 31 Mar 2016 08:00 AM SAST\" temp=\"58\" text=\"Mostly Cloudy\"/>" +
"</yweather:condition>" +
"</item>" +
"</channel>" +
"</results>" +
"</query>" +
"</Root>";
XDocument doc = XDocument.Parse(xml);
string innertext = doc.Descendants().Where(x => x.Name.LocalName == "condition").Select(y => y.Value).FirstOrDefault();
string pattern = "\\s?(?'name'[^=]+)=\"(?'value'[^\"]+)\"";
MatchCollection matches = Regex.Matches(innertext, pattern);
foreach (Match match in matches)
{
Console.WriteLine("Name : {0}, Value : {1}", match.Groups["name"].Value, match.Groups["value"].Value);
}
Console.ReadLine();
}
}
}

How to create an XML file from this c# class?

I want to create an XML file from the following c# class and vice-verse. How can i do this?
public class Settings
{
public string Id { get; set; }
public string Name { get; set; }
public string Value { get; set; }
public string ParentId { get; set; }
public List<Settings> SubSettings { get; set; }
public bool IsRoot
{
get
{
return string.IsNullOrEmpty(ParentId);
}
}
}
You can serialize a class in C# using XmlSerializer like this:
var s = new Settings()
{
Id = "id",
Name = "name",
ParentId = "parentId",
Value = "value",
SubSettings = new List<Settings>()
{
new Settings()
{
Id = "subId",
Name = "subName",
ParentId = "subParentId",
Value = "subValue",
SubSettings = new List<Settings>()
}
}
};
XmlSerializer serializer = new XmlSerializer(typeof(Settings));
string fileName = "C:\\test.xml";
using (FileStream fs = File.Open(fileName, FileMode.CreateNew))
{
serializer.Serialize(fs, s);
}
This is the result that I get:
<?xml version="1.0"?>
<Settings xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Id>id</Id>
<Name>name</Name>
<Value>value</Value>
<ParentId>parentId</ParentId>
<SubSettings>
<Settings>
<Id>subId</Id>
<Name>subName</Name>
<Value>subValue</Value>
<ParentId>subParentId</ParentId>
<SubSettings />
</Settings>
</SubSettings>
</Settings>
You can then deserialize it back to an object like this:
XmlSerializer serializer = new XmlSerializer(typeof(Settings));
Stream fs = new FileStream("C:\\test.xml", FileMode.Open);
Settings settings = (Settings)serializer.Deserialize(fs);

Categories

Resources