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);
Related
C#:
XElement Xml = null;
var apiResponse = response.Content.ReadAsStringAsync().Result;
Xml = Newtonsoft.Json.JsonConvert.DeserializeObject<XElement>(apiResponse);
XML response from above code:
I'm having errors with Images xml part, while converting it to List,
I tried so many options, Please provide suggestion from below
<root>
<Column1>
<ID>2702</ID>
<Desc>Failed</Desc>
<Address>Florida</Address>
<Date>2019-04-30T23:10:36.79</Date>
<**Images**>
<Image>
<File>1-RRamos.PNG</File>
</Image>
<Image>
<File>RRamos.PNG</File>
</Image>
<Image>
<File>3-RRamos.PNG</File>
</Image>
</**Images**>
</Column1>
</root>
Trying to convert from xml to List from below
public class objClass
{
public string ID{ get; set; }
public string Desc{ get; set; }
public string Address { get; set; }
public DateTime? Date{ get; set; }
//public string[] ImageFileNames { get; set; }
public List<Images> FileName { get; set; }
}
public class FileName
{
public string File{ get; set; }
}
List<objClass> list = Xml.Elements("ID").Select(sv => new objClass()
{
ID= (string)sv.Element("ID"),
Desc= (string)sv.Element("Desc"),
Address = (string)sv.Element("Address"),
Date= (DateTime?)sv.Element("Date"),
//**,Images = (List)sv.Element("Images")**
}).ToList();
From XML response, trying to convert it to List.
You can't use the Newtonsoft.Json library to deserialize from an XML.
Solution 1: Convert XML to list via XPath
Parse XML string to XDocument.
With XPath: "//root/Column1", select the <Column1> element.
using System.Xml;
using System.Xml.Linq;
using System.Xml.Serialization;
using System.Xml.XPath;
var apiResponse = await response.Content.ReadAsStringAsync();
XDocument #Xml = XDocument.Parse(apiResponse);
List<ObjClass> list = #Xml.XPathSelectElements("//root/Column1")
.Select(sv => new ObjClass()
{
ID = (string)sv.Element("ID"),
Desc = (string)sv.Element("Desc"),
Address = (string)sv.Element("Address"),
Date = (DateTime?)sv.Element("Date"),
Images = sv.Element("Images")
.Elements("Image")
.Select(x => new Image
{
File = (string)x.Element("File")
})
.ToList()
})
.ToList();
Solution 2: Deserialize XML
This answer will be a bit complex but work the same as Solution 1.
Write the apiResponse value into MemoryStream.
Deserialize the MemoryStream via XmlSerializer as Root.
Extract root.Column and add into list.
[XmlRoot(ElementName = "root")]
public class Root
{
[XmlElement("Column 1")]
public ObjClass Column { get; set; }
}
public class ObjClass
{
public string ID { get; set; }
public string Desc { get; set; }
public string Address { get; set; }
public DateTime? Date { get; set; }
[XmlArray]
[XmlArrayItem(typeof(Image), ElementName = "Image")]
public List<Image> Images { get; set; }
}
public class Image
{
public string File { get; set; }
}
using System.Xml;
using System.Xml.Serialization;
using System.IO;
var apiResponse = await response.Content.ReadAsStringAsync();
using var stream = new MemoryStream();
using var writer = new StreamWriter(stream);
writer.Write(apiResponse);
writer.Flush();
stream.Position = 0;
XmlSerializer xmlSerializer = new XmlSerializer(typeof(Root));
Root root = (Root)xmlSerializer.Deserialize(stream);
List<ObjClass> list = new List<ObjClass>();
list.Add(root.Column);
Concern:
Use await instead of Task<T>.Result as Task<T>.Result will block the calling thread until it (the task) is completed. With await, the task is waited to be completed asynchronously. Reference: What is the difference between await Task and Task.Result?
public class objClass
{
public string ID { get; set; }
public string Desc { get; set; }
public string Address { get; set; }
public DateTime? Date { get; set; }
public string[] ImageFileNames { get; set; }
}
var list = Xml.Elements("root").Elements("Column1")
.Select(sv => new objClass()
{
ID = (string)sv.Element("ID"),
Desc = (string)sv.Element("Desc"),
Address = (string)sv.Element("Address"),
Date = (DateTime?)sv.Element("Date"),
ImageFileNames = sv.Element("Images")
.Elements("Image")
.Select(i => (string)i.Element("File"))
.ToArray(),
})
.ToList();
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>
.
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);
I have following xml :
in other standard xml like this question here we have no problem but in php web service :
http://sandoghche.com/WebService
for inbox check my inbox xml is this:
<?xml version=\"1.0\" encoding=\"UTF-8\" ?>
<Result>
<text_message>
<id>509</id>
<message><![CDATA[a]]></message>
<time>1323519941</time>
<message_phone>
<cellphone>09196070718</cellphone>
</message_phone>
</text_message>
<text_message>
<id>507</id>
<message>1</message>
<time>1323519803</time>
<message_phone>
<cellphone>09360437392</cellphone>
</message_phone>
</text_message>
<text_message>
<id>303</id>
<message><![CDATA[smsm text]]></message>
<time>1318343296</time>
<message_phone>
<cellphone>09354338365</cellphone>
</message_phone>
</text_message>
<text_message>
<id>219</id>
<message><![CDATA[my sms texts here]]></message>
<time>1316154042</time>
<message_phone>
<cellphone>09127930265</cellphone>
</message_phone>
</text_message>
<text_message>
<id>217</id>
<message>2</message>
<time>1316090189</time>
<message_phone>
<cellphone>09195533234</cellphone>
</message_phone>
</text_message>
</Result>
for this I wrote the following code
public class SMSData
{
public int id { set; get; }
public string message { set; get; }
public string cellphone { set; get; }
}
string data = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?><Result><text_message><id>509</id><message><![CDATA[a]]></message><time>1323519941</time><message_phone><cellphone>09196070718</cellphone></message_phone></text_message><text_message><id>507</id><message>1</message><time>1323519803</time><message_phone><cellphone>09360437392</cellphone></message_phone></text_message><text_message><id>303</id><message><![CDATA[ممنون.شما؟]]></message><time>1318343296</time><message_phone><cellphone>09354378365</cellphone></message_phone></text_message><text_message><id>219</id><message><![CDATA[سلام اقاي طباطبايي لينك مربوط به ورود اعضا به وبلاگ روي صفحه فيلتر مي رود با احترام احدي]]></message><time>1316154042</time><message_phone><cellphone>09127960265</cellphone></message_phone></text_message><text_message><id>217</id><message>2</message><time>1316090189</time><message_phone><cellphone>09195523234</cellphone></message_phone></text_message></Result>";
Stream s = GenerateStreamFromString(data);
XmlReader xr = XmlReader.Create(s);
while (xr.Read())
{
if ((xr.NodeType == XmlNodeType.Element) && (xr.Name == "text_message"))
{
if (xr.HasValue)
{
string id = xr.GetAttribute("id");
string message = xr.GetAttribute("message");
}
}
}
and this code
Dictionary<int, string> myDictionary = new Dictionary<int, string>();
XmlDocument xml = new XmlDocument();
xml.LoadXml(data);
XmlNodeList xnList = xml.SelectNodes("/Result");
foreach (XmlNode xn in xnList)
{
but can't catch values on this xml document.
Is there a clean way to do this?
It is easier to use the built-in Serializers for these kind of things, like the XmlSerializer or the DataContractSerializer. I used the latter and tested your XML with the following snippet.
First annotate your SMSData class and create a new class to hold the Message_phone elements in a new class:
[DataContract(Name="text_message",Namespace = "")]
public class SMSData
{
[DataMember(Order =1)]
public int id { set; get; }
[DataMember(Order = 2)]
public string message { set; get; }
[DataMember(Order = 3)]
public int time { set; get; }
[DataMember(Order = 4)]
public Message_phone message_phone { set; get; }
// for easy access to cellphone
public string cellphone {
get
{
return message_phone!=null?message_phone.cellphone:null;
}
}
}
[DataContract(Name="message_phone",Namespace = "")]
public class Message_phone
{
[DataMember]
public string cellphone { set; get; }
}
and then create an instance of the DataContractSerializer for your array of SMSData, and call ReadObject on it like so:
Stream s = GenerateStreamFromString(data);
var ds = new DataContractSerializer(
typeof(SMSData[]), // array of SMSdata
"Result", // top level element
"", // empty namespace
new List<Type> { typeof(SMSData[])} );
var smsdata = (SMSData[]) ds.ReadObject(XmlReader.Create(s));
// smsdata now holds the SMSData from the Xml file
I am trying to do a XML parser which will extract data from a website using REST service, the protocol for communication is HTTP, the data I get is in XML format, and I get to the data I need after several requests to different addresses on the server. I need to parse this data to c# objects so I can operate with them lately.
The information on the server is on 5 levels( I am willing to make work only 4 of them for know)
1-List of vendors
2-List of groups
3-List of subgroups
4-List of products
5-List of full information about products
After I get to 4th level I need to check if the product is in my database or if it has different details so I can add or update it.
With "GET" request to a server I get XML with this structure:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<vendors>
<vendor>
<id>someID</id>
<name>someName</name>
</vendor>
<vendor>
<id>someId1</id>
<name>somename1</name>
</vendor>
</vendors>
XML structure for groups is the same :
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<groups vendor_id="43153185318">
<group>
<id>someID</id>
<name>someName</name>
</group>
<group>
<id>someId1</id>
<name>somename1</name>
</group>
The XML structure is analogical for subgroups and products, except that for products I have more elements like catalog_num, price etc.
I made the classes as follows :
public class VendorList
{
public List<Vendor> vendor_list { get; set; }
public VendorList()
{
vendor_list = new List<Vendor>();
}
}
public class Vendor
{
public string id { get; set; }
public string name { get; set; }
public List<Group> groups_list { get; set; }
public Vendor()
{
id = "N/A";
name = "N/A";
groups_list = new List<Group>();
}
}
public class Group
{
public string id { get; set; }
public string name { get; set; }
public List<SubGroup> subgroup_list { get; set; }
public Group()
{
id = "N/A";
name = "N/A";
subgroup_list = new List<SubGroup>();
}
}
public class SubGroup
{
public string id { get; set; }
public string name { get; set; }
public List<Product> product_list { get; set; }
public SubGroup()
{
id = "N/A";
name = "N/A";
product_list = new List<Product>();
}
}
public class Product
{
public string available { get; set; }
public string catalog_num { get; set; }
public string code { get; set; }
public string currency { get; set; }
public string description { get; set; }
public string haracteristics { get; set; }
public string product_id { get; set; }
public string model { get; set; }
public string name { get; set; }
public string price { get; set; }
public string price_dds { get; set; }
public string picture_url { get; set; }
public Product()
{
available = "N/A";
catalog_num = "N/A";
code = "N/A";
currency = "N/A";
description = "N/A";
haracteristics = "N/A";
product_id = "N/A";
model = "N/A";
name = "N/A";
price = "N/A";
price_dds = "N/A";
picture_url = "N/A";
}
}
and the Parser method like this :
public static void FillVendor(string url)
{
string result = GetXMLstream(url);
var vendors = new VendorList();
XmlDocument doc = new XmlDocument();
doc.Load(new StringReader(result));
doc.Save(#"D:/proba/proba.xml");
XDocument d = XDocument.Load(#"D:/proba/proba.xml");
vendors.vendor_list = (from c in d.Descendants("vendor")
select new Vendor()
{
id = c.Element("id").Value,
name = c.Element("name").Value
}).ToList<Vendor>();
foreach (Vendor v in vendors.vendor_list)
{
FillGroups(v.id);
}
}
public static void FillGroups(string vendorID)
{
string url = "main address" + vendorID;
string result = GetXMLstream(url);
var group = new Vendor();
XmlDocument doc = new XmlDocument();
doc.Load(new StringReader(result));
doc.Save(#"D:/proba/proba1.xml");
XDocument d = XDocument.Load(#"D:/proba/proba1.xml");
group.groups_list = (from g in d.Descendants("group")
select new Group()
{
id = g.Element("id").Value,
name = g.Element("name").Value
}).ToList<Group>();
foreach (Group g in group.groups_list)
{
FillSubGroup(vendorID, g.id);
}
}
public static void FillSubGroup(string vendorID, string groupID)
{
string url = "main address" + vendorID+"/"+groupID;
string result = GetXMLstream(url);
var subgroup = new Group();
XmlDocument doc = new XmlDocument();
doc.Load(new StringReader(result));
doc.Save(#"D:/proba/proba2.xml");
XDocument d = XDocument.Load(#"D:/proba/proba2.xml");
subgroup.subgroup_list = (from g in d.Descendants("subgroup")
select new SubGroup()
{
id = g.Element("id").Value,
name = g.Element("name").Value
}).ToList<SubGroup>();
foreach (SubGroup sb in subgroup.subgroup_list)
{
FillProduct(vendorID, groupID, sb.id);
}
}
public static void FillProduct(string vendorID,string groupID,string subgroupID)
{
string url = "main address" + vendorID + "/" + groupID+"/"+subgroupID;
string result = GetXMLstream(url);
var product = new SubGroup();
XmlDocument doc = new XmlDocument();
doc.Load(new StringReader(result));
doc.Save(#"D:/proba/proba2.xml");
XDocument d = XDocument.Load(#"D:/proba/proba2.xml");
product.product_list = (from g in d.Descendants("subgroup")
select new Product()
{
available = g.Element("available").Value,
catalog_num = g.Element("catalog_num").Value,
code = g.Element("code").Value,
currency = g.Element("currency").Value,
description = g.Element("description").Value,
haracteristics = g.Element("haracteristics").Value,
product_id = g.Element("id").Value,
model = g.Element("model").Value,
name = g.Element("name").Value,
price = g.Element("price").Value,
price_dds = g.Element("price_dds").Value,
picture_url = g.Element("small_picture").Value,
}).ToList<Product>();
}
But after finishing parsing I try to check if my Lists are populated with objects, but I get an error which says that they are null "NullReferenceException"
So my question is did I make classes properly and is my parsing method right ( you can suggest how to parse the xml without creating a file on my computer) and if I didn't where is my mistake and how should I make it work properly?
Thanks in advance!
modify this line add 's'( vendor -> vendors)
-> vendors.vendor_list = (from c in d.Descendants("vendor")
and the same case for group -> groups
Instead of making the classes yourself.
Create a properly formatted XML Schema either manually or with Visual Studio and then from that XSD File you've created generate your C# Classes.