I am trying to send response as per below to the user. I am facing issue for node ITEM in which ( Type, For, Amount, Description & Rate ) present in the node as per below. But when i am trying to generate the output it is not generation output as per below for this node.
EXPECTED OUTPUT
<ANF>
<QUOTEID>951C3532</QUOTEID>
<CHARGE>161.98</CHARGE>
<ITEMIZEDCHARGES>
<ITEM TYPE="CHARGE" FOR="FREIGHT" AMOUNT="914.41" DESCRIPTION="65 LB CL125, 1 PLT # 94 x 48 x 12 IN" />
<ITEM TYPE="DISCOUNT" FOR="SHIPPER" AMOUNT="-832.11" DESCRIPTION="SHIPPER DISCOUNT" RATE="91%" />
<ITEM TYPE="CHARGE" FOR="MCADJ" AMOUNT="137.70" DESCRIPTION="ABSOLUTE MIN CHARGE ADJUSTMENT" />
</ITEMIZEDCHARGES>
<NOTES>
</NOTES>
<NUMERRORS>0</NUMERRORS>
</ANF>
I have generated the object for this xml response as per below
namespace ResponseXML
{
[XmlRoot(ElementName="ITEM")]
public class ITEM {
[XmlAttribute(AttributeName="TYPE")]
public string TYPE { get; set; }
[XmlAttribute(AttributeName="FOR")]
public string FOR { get; set; }
[XmlAttribute(AttributeName="AMOUNT")]
public string AMOUNT { get; set; }
[XmlAttribute(AttributeName="DESCRIPTION")]
public string DESCRIPTION { get; set; }
[XmlAttribute(AttributeName="RATE")]
public string RATE { get; set; }
}
[XmlRoot(ElementName="ITEMIZEDCHARGES")]
public class ITEMIZEDCHARGES {
[XmlElement(ElementName="ITEM")]
public List<ITEM> ITEM { get; set; }
}
[XmlRoot(ElementName="ANF")]
public class ANF {
[XmlElement(ElementName="QUOTEID")]
public string QUOTEID { get; set; }
[XmlElement(ElementName="CHARGE")]
public string CHARGE { get; set; }
[XmlElement(ElementName="ITEMIZEDCHARGES")]
public ITEMIZEDCHARGES ITEMIZEDCHARGES { get; set; }
[XmlElement(ElementName="NOTES")]
public string NOTES { get; set; }
[XmlElement(ElementName="NUMERRORS")]
public string NUMERRORS { get; set; }
}
}
My code output ITEMIZEDCHARGES
<ITEMIZEDCHARGES>
<ITEM>
<ITEM>
<AMOUNT>45.09</AMOUNT>
<DESCRIPTION></DESCRIPTION>
<FOR i:nil="true" />
<RATE></RATE>
<TYPE></TYPE>
</ITEM>
</ITEM>
</ITEMIZEDCHARGES>
My Code for adding values is as below in object
ITEMIZEDCHARGES _fItem = new ITEMIZEDCHARGES();
List<ITEM> fitmes = new List<ITEM>();
ITEM _item = new ITEM();
_item.AMOUNT = Convert.ToString(zipDetails.Rate);
_item.RATE = "";
_item.TYPE = "";
_item.DESCRIPTION = "";
fitmes.Add(_item);
_fItem.ITEM = fitmes;
fn.ITEMIZEDCHARGES = _fItem;
Can you please advice what i am doing mistake.
Code for response from code
[System.Web.Http.HttpPost]
[System.Web.Http.Route("GetQuote")]
[ResponseType(typeof(IEnumerable<ABF>))]
public HttpResponseMessage GetOrderPriceQuotetest(HttpRequestMessage request)
{
var abf = request.Content.ReadAsStringAsync().Result;
try
{
if (abf != null)
{
XmlSerializer serializer = new XmlSerializer(typeof(OrderPriceRequest.ABF));
using (StringReader reader = new StringReader(abf))
{
OrderPriceRequest.ABF testReq = (OrderPriceRequest.ABF)serializer.Deserialize(reader);
if (testReq != null)
{
ANF fn = new ANF();
fn.CHARGE = 0;
fn.QUOTEID = "";
ITEMIZEDCHARGES _fItem = new ITEMIZEDCHARGES();
List<ITEM> fitmes = new List<ITEM>();
ITEM _item = new ITEM();
_item.AMOUNT = "10";
_item.RATE = "";
_item.TYPE = "";
_item.DESCRIPTION = "";
fitmes.Add(_item);
_fItem.ITEMS = fitmes;
fn.ITEMIZEDCHARGES = _fItem;
return Request.CreateResponse(HttpStatusCode.OK, fn);
}
else
{
ANF fn = new ANF();
return Request.CreateResponse(HttpStatusCode.OK, fn);
}
}
}
else
{
return Request.CreateResponse(HttpStatusCode.BadRequest, abf);
}
}
catch (Exception ex)
{
return request.CreateResponse(HttpStatusCode.BadRequest);
}
}
Related
I have an xml file and its content is as follows. I want to add the information of the flights in this file to the datagridview. The columns I will create in the datagridview are
flight_id, flight_description, flight_date, instructor_num, instructor_name, student_num, student_name
<?xml version="1.0" encoding="utf-8"?>
<Simulator>
<Flight ID="1" Description="sunny" Date="2022-09-09">
<Instructor Num="6">
<Name>matt</Name>
<Surname>matt</Surname>
<Rank>matt</Rank>
</Instructor>
<Student Num="66">
<Name>matt</Name>
<Surname>matt</Surname>
<Rank>matt</Rank>
</Student>
<Operator Num="666">
<Name>matt</Name>
<Surname>matt</Surname>
<Rank>matt</Rank>
</Operator>
<Technician Num="6666">
<Name>matt</Name>
<Surname>matt</Surname>
<Rank>matt</Rank>
</Technician>
<ErrorLOGS>
<Logs Hour_Date="2022-09-09T09:12:00" ID="1">
<ErrorGUI>checkbox</ErrorGUI>
<ErrorType>high</ErrorType>
<ProgramPage>Failures</ProgramPage>
<ErrorStartTime>PT9H12M23S</ErrorStartTime>
</Logs>
<Logs Hour_Date="2022-09-09T09:12:00" ID="1">
<ErrorGUI>checkbox</ErrorGUI>
<ErrorType>high</ErrorType>
<ProgramPage>Page</ProgramPage>
<ErrorStartTime>PT9H12M23S</ErrorStartTime>
</Logs>
</ErrorLOGS>
</Flight>
<Flight ID="2" Description="test flight">
.................like flight1.........
</Flight>
</Simulator>
I tried something like this but failed
string inputpath = Application.StartupPath + "\\Data.xml";
XmlDocument doc = new XmlDocument();
doc.LoadXml(inputpath);
IEnumerable<string> names = doc.Root.Descendants("Flight").Select(e => e.Attribute("ID") , e.Attribute("Description"), e.Attribute("Date")).Value);
Use my previous posting code. Added MakeDataTable. Than you can make the DataSource of dgv the datatable : datagridview1.DataSource = dt.
public class Simulator
{
XDocument doc = null;
public Simulator(string filename)
{
doc = XDocument.Load(filename);
}
public Simulator(string id, string description)
{
string ident = "<?xml version=\"1.0\" encoding=\"utf-8\"?><Simulator></Simulator>";
doc = XDocument.Parse(ident);
XElement flight = new XElement("Flight", new object[] {
new XAttribute("ID", id),
new XAttribute("Description", description)
});
doc.Root.Add(flight);
}
public string AddUser(string flightID, string role, string number, string name, string surname, string rank)
{
XElement flight = doc.Descendants("Flight").Where(x => (string)x.Attribute("ID") == flightID).FirstOrDefault();
if (flight != null)
{
XElement user = new XElement(role, new object[] {
new XAttribute("Num", number),
new XElement("Name", name),
new XElement ("Surname", surname),
new XElement("Rank", rank)
});
flight.Add(user);
return "GOOD";
}
else
{
return "Flight ID doesn't exist";
}
}
public string AddFlight(string flightID, string description)
{
XElement flight = doc.Descendants("Flight").Where(x => (string)x.Attribute("ID") == flightID).FirstOrDefault();
if (flight == null)
{
flight = new XElement("Flight", new object[] {
new XAttribute("ID", flightID),
new XAttribute("Description", description)
});
doc.Root.Add(flight);
return "Good";
}
else
{
return "Flight ID already exists";
}
}
public string AddErrors(string flightID, XElement errorLog)
{
XElement flight = doc.Descendants("Flight").Where(x => (string)x.Attribute("ID") == flightID).FirstOrDefault();
if (flight == null)
{
return "Flight ID doesn't exist";
}
else
{
flight.Add(errorLog);
return "GOOD";
}
}
public void WriteXml(string filename)
{
doc.Save(filename);
}
public DataTable MakeDataTable()
{
DataTable dt = new DataTable();
dt.Columns.Add("flight_id", typeof(int));
dt.Columns.Add("flight_description", typeof(string));
dt.Columns.Add("flight_date",typeof(DateTime));
dt.Columns.Add("instructor_num", typeof(int));
dt.Columns.Add("instructor_name", typeof(string));
dt.Columns.Add("student_num", typeof(int));
dt.Columns.Add("student_name", typeof(string));
foreach (XElement flight in doc.Descendants("Flight"))
{
DataRow row = dt.Rows.Add();
int iD = (int)flight.Attribute("ID");
row["flight_id"] = iD;
string description = (string)flight.Attribute("Description");
row["flight_description"] = description;
DateTime date = (DateTime)flight.Attribute("Date");
row["flight_date"] = date;
XElement xStudent = flight.Element("Student");
if (xStudent != null)
{
int studentNum = (int)xStudent.Attribute("Num");
row["student_num"] = studentNum;
string studentName = (string)xStudent.Element("Name");
row["student_name"] = studentName;
}
XElement xInstructor = flight.Element("Instructor");
if (xInstructor != null)
{
int instructorNum = (int)xStudent.Attribute("Num");
row["instructor_num"] = instructorNum;
string instructorName = (string)xStudent.Element("Name");
row["student_name"] = instructorName;
}
}
return dt;
}
}
Try to create classes for the simulator and deserialize it like this
public Simulator FromXml(string value)
{
using (TextReader reader = new StringReader(value))
{
return new XmlSerializer(Simulator).Deserialize(reader);
}
}
public partial class Simulator
{
[JsonProperty("Flight")]
public Flight Flight { get; set; }
}
public partial class Flight
{
[JsonProperty("Instructor")]
public Instructor Instructor { get; set; }
[JsonProperty("Student")]
public Instructor Student { get; set; }
[JsonProperty("Operator")]
public Instructor Operator { get; set; }
[JsonProperty("Technician")]
public Instructor Technician { get; set; }
[JsonProperty("ErrorLOGS")]
public ErrorLogs ErrorLogs { get; set; }
}
public partial class ErrorLogs
{
[JsonProperty("Logs")]
public Log[] Logs { get; set; }
}
public partial class Log
{
[JsonProperty("ErrorGUI")]
public string ErrorGui { get; set; }
[JsonProperty("ErrorType")]
public string ErrorType { get; set; }
[JsonProperty("ProgramPage")]
public string ProgramPage { get; set; }
[JsonProperty("ErrorStartTime")]
public string ErrorStartTime { get; set; }
}
public partial class Instructor
{
[JsonProperty("Name")]
public string Name { get; set; }
[JsonProperty("Surname")]
public string Surname { get; set; }
[JsonProperty("Rank")]
public string Rank { get; set; }
}
private void gridFilter_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex > -1 && e.ColumnIndex > -1)
{
gridFilter.Rows[e.RowIndex].Selected = true;
string selectedValue = gridFilter.Rows[e.RowIndex].Cells[0].FormattedValue.ToString();
XDocument doc = XDocument.Load(inputpath);
List<XElement> flights = doc.Descendants("Flight").ToList();
foreach (XElement flight in flights)
{
string idSelect1 = (string)flight.Attribute("ID");
if (selectedValue == idSelect1) {
XElement xLogs = flight.Element("Logs");
if (xLogs != null)
{
string ErrorGUI = (string)xLogs.Element("ErrorGUI");
string ErrorType = (string)xLogs.Element("ErrorType");
string ProgramPage = (string)xLogs.Element("ProgramPage");
listBox.Items.Add(ErrorGUI);
listBox.Items.Add(ErrorType);
listBox.Items.Add(ProgramPage);
}
}
}
}
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I got a class which represents a soccerplayer:
public class PlayerExtended
{
[XmlAttribute("id")] public string Id { get; set; }
[XmlAttribute("shortName")] public string ShortName { get; set; }
[XmlAttribute("firstName")] public string FirstName { get; set; }
[XmlAttribute("surName")] public string SurName { get; set; }
[XmlAttribute("shirtNumber")] public string ShirtNumber { get; set; }
[XmlAttribute("actions")] public string Actions { get; set; }
[XmlAttribute("substitude")] public string Substitude { get; set; }
[XmlAttribute("grade")] public string Grade { get; set; }
[XmlAttribute("iconSmall")] public string IconSmall { get; set; }
[XmlAttribute("position")] public string Position { get; set; }
[XmlAttribute("squadPositionID")] public string SquadPositionId { get; set; }
[XmlAttribute("squadPosition")] public string SquadPosition { get; set; }
[XmlAttribute("inMinute")] public string InMinute { get; set; }
[XmlAttribute("outMinute")] public string OutMinute { get; set; }
[XmlAttribute("captain")] public string Captain { get; set; }
}
After assigning values to the properties one of the players looks like this:
The property "Actions" is an empty string (NOT NULL).
If I serialize it it looks like this:
<player id="51641" shortName="Bürki" firstName="Roman" surName="Bürki" shirtNumber="1" substitude="starter" grade="2,5" iconSmall="xxx.whatever.com" position="11" squadPositionID="1" squadPosition="Torwart"/>
But I want it to look like this:
<player id="51641" shortName="Bürki" firstName="Roman" surName="Bürki" shirtNumber="1" actions="" substitude="starter" grade="2,5" iconSmall="xxx.whatever.com" position="11" squadPositionID="1" squadPosition="Torwart"/>
So how do I serialize an XmlAttribute which is an empty string?
How are you generating your XML? I cannot seem to reproduce your issue.
public class Program
{
public static void Main(string[] args)
{
using var writer = new StringWriter();
var serializer = new XmlSerializer(typeof(Player));
serializer.Serialize(writer, new Player { Name = "", Age = 25 });
Console.WriteLine(writer);
}
}
public class Player
{
[XmlAttribute("name")]
public string Name { get; set; }
[XmlAttribute("age")]
public int Age { get; set; }
}
The code above results in the name attribute in the format you desire (name=""). Let me know if this answer is sufficient for you.
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Xml.Serialization;
// Runtime Target = .NET Core v2.1 or .NET Core v3.1
namespace XmlSerialize
{
class Program
{
static void Main(string[] args)
{
var mickey = new Employee { FirstName = "Mickey", LastName = "Mouse" };
var asterix = new Employee { FirstName = "Asterix", LastName = "" };
var obelix = new Employee { FirstName = "Obelix", LastName = null };
var nixnix = new Employee { FirstName = null, LastName = null };
Console.WriteLine(SerializeXml(mickey) + SerializeXml(asterix) + SerializeXml(obelix) + SerializeXml(nixnix));
}
public static string SerializeXml<T>(T instanceToSerialize)
{
var serializer = new XmlSerializer(instanceToSerialize.GetType(), string.Empty);
var result = string.Empty;
using (var stringWriter = new StringWriter())
{
serializer.Serialize(stringWriter, instanceToSerialize);
result = stringWriter.ToString();
}
return result;
}
}
[XmlRoot("Employee")]
public sealed class Employee
{
[XmlAttribute("FirstName")]
public string FirstName { get; set; }
[XmlIgnore]
public string LastName { get; set; }
[XmlAttribute("LastName")]
public string SerializableLastName // <------------ Might this help?
{
get { return this.LastName ?? string.Empty; }
set { this.LastName = value; }
}
[XmlElement]
public List<string> Skills { get; set; }
}
}
Output
<?xml version="1.0" encoding="utf-16"?>
<Employee FirstName="Mickey" LastName="Mouse" />
<Employee FirstName="Asterix" LastName="" />
<Employee FirstName="Obelix" LastName="" />
<Employee LastName="" />
setting the property value to string.Empty will do the trick. I am using XmlSerializer to convert the object to XML. If I set the property to string.Empty, this will result as empty attribute in XML. Here is the example
public class TestClass
{
[XmlAttribute("test1")]
public string test1 { get; set; }
[XmlAttribute("test2")]
public string test2 { get; set; }
}
var dd = new List<TestClass>();
dd.Add( new TestClass() { test1 = "asdf", test2 = string.Empty }); //will generate empty attribute for test2
dd.Add( new TestClass() { test1 = "asdf" }); //the attribute test2 will be ignored
using (var stringwriter = new System.IO.StringWriter())
{
var serializer = new XmlSerializer(dd.GetType());
serializer.Serialize(stringwriter, dd);
Console.WriteLine( stringwriter.ToString());
}
Output
<?xml version="1.0" encoding="utf-16"?>
<ArrayOfTestClass xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<TestClass test1="asdf" test2="" />
<TestClass test1="asdf" />
</ArrayOfTestClass>
I want to write my items by JSON format, but My files empty. Here is my two class:
public class DocPart
{
public string Title { get; set; }
public bool Checked { get; set; }
}
public class DocConfig
{
public List<DocPart> Parts { get; set; }
public static DocConfig LoadFromString(string jsonData)
{
var config = new DocConfig();
config.Parts = new List<DocPart>();
var part = new DocPart
{
Title = "chapter1",
"chapter2",
Checked = checkBox1.Checked,
checkbox2.Checked
};
config.Parts.Add(part);
var configString = config.SaveToString();
File.WriteAllText(#"C:\link to my file", configString);
var configString = File.ReadAllText(#"C:\link to my file");
var config = DocConfig.LoadFromString(configString);
foreach (var part in config.Parts)
{
if (part.Title == "chapter1")
chekbox1.Checked = part.Checked;
if (part.Title == "chapter2")
checkbox2.Checked = part.Checked;
var serializer = new DataContractJsonSerializer(typeof(DocConfig));
var ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonData));
var config = (DocConfig)serializer.ReadObject(ms);
return config;
}
}
public string SaveToString()
{
var serializer = new DataContractJsonSerializer(typeof(DocConfig));
var ms = new MemoryStream();
serializer.WriteObject(ms, this);
return Encoding.UTF8.GetString(ms.ToArray());
}
}
So I run my program, everything looks okey, but my file is still empty without any JSON format data. Maybe you could help me?
Thanks.
public class DocPart
{
public string Title { get; set; }
public bool Checked { get; set; }
}
public class DocConfig
{
public List<DocPart> Parts { get; set; }
public static DocConfig LoadFromString()
{
var config = new DocConfig();
config.Parts = new List<DocPart>();
var part1 = new DocPart
{
Title = "chapter1",
Checked = checkBox1.Checked
};
config.Parts.Add(part1);
var part2 = new DocPart
{
Title = "chapter2",
Checked = checkBox2.Checked
};
config.Parts.Add(part2);
var configString = config.SaveToString();
File.WriteAllText(#"d:\temp\test.json", configString);
configString = File.ReadAllText(#"d:\temp\test.json");
var ms = new MemoryStream(Encoding.UTF8.GetBytes(configString));
var serializer = new DataContractJsonSerializer(typeof(DocConfig));
config = (DocConfig)serializer.ReadObject(ms);
foreach (var part in config.Parts)
{
if (part.Title == "chapter1")
{
chekbox1.Checked = part.Checked;
Debug.WriteLine("chapter1" + part.Checked);
}
if (part.Title == "chapter2")
{
checkbox2.Checked = part.Checked;
Debug.WriteLine("chapter2" + part.Checked);
}
}
return config;
}
public string SaveToString()
{
var serializer = new DataContractJsonSerializer(typeof(DocConfig));
var ms = new MemoryStream();
serializer.WriteObject(ms, this);
return Encoding.UTF8.GetString(ms.ToArray());
}
}
Here's a really simple example I mocked up for you...
void Main()
{
const string filePath = #"C:\FilePath\json.txt";
const string testJson = #"{""glossary"": {""title"": ""example glossary"", ""GlossDiv"": {""title"": ""S"", ""GlossList"": {""GlossEntry"": {""ID"": ""SGML"", ""SortAs"": ""SGML"", ""GlossTerm"": ""Standard Generalized Markup Language"", ""Acronym"": ""SGML"", ""Abbrev"": ""ISO 8879:1986"", ""GlossDef"": {""para"": ""A meta-markup language, used to create markup languages such as DocBook."", ""GlossSeeAlso"": [""GML"", ""XML""]}, ""GlossSee"": ""markup""}}}}}";
// Now we have our Json Object...
SampleJson sample = JsonConvert.DeserializeObject<SampleJson>(testJson);
// We convert it back into a string with indentation...
string jsonString = JsonConvert.SerializeObject(sample, Newtonsoft.Json.Formatting.Indented);
// Now simply save to file...
using (StreamWriter writer = new StreamWriter(filePath))
{
writer.WriteLine(jsonString);
}
Process.Start(filePath);
}
// The following classes are what the `testJson` string is deserialized into.
public class GlossDef
{
[JsonProperty("para")]
public string Para { get; set; }
[JsonProperty("GlossSeeAlso")]
public string[] GlossSeeAlso { get; set; }
}
public class GlossEntry
{
[JsonProperty("ID")]
public string ID { get; set; }
[JsonProperty("SortAs")]
public string SortAs { get; set; }
[JsonProperty("GlossTerm")]
public string GlossTerm { get; set; }
[JsonProperty("Acronym")]
public string Acronym { get; set; }
[JsonProperty("Abbrev")]
public string Abbrev { get; set; }
[JsonProperty("GlossDef")]
public GlossDef GlossDef { get; set; }
[JsonProperty("GlossSee")]
public string GlossSee { get; set; }
}
public class GlossList
{
[JsonProperty("GlossEntry")]
public GlossEntry GlossEntry { get; set; }
}
public class GlossDiv
{
[JsonProperty("title")]
public string Title { get; set; }
[JsonProperty("GlossList")]
public GlossList GlossList { get; set; }
}
public class Glossary
{
[JsonProperty("title")]
public string Title { get; set; }
[JsonProperty("GlossDiv")]
public GlossDiv GlossDiv { get; set; }
}
public class SampleJson
{
[JsonProperty("glossary")]
public Glossary Glossary { get; set; }
}
I'm new to RestSharp and trying to access my subsonic server through the subsonic-api.
Every Response in wrapped in a subsonic-response Tag, e.g.
<subsonic-response xmlns="http://subsonic.org/restapi"
status="ok" version="1.10.1">
<artists ignoredArticles="The El La Los Las Le Les">
<index name="A">
<artist id="5449" name="A-Ha" coverArt="ar-5449" albumCount="4"/>
<artist id="5421" name="ABBA" coverArt="ar-5421" albumCount="6"/>
<artist id="5432" name="AC/DC" coverArt="ar-5432" albumCount="15"/>
<artist id="6633" name="Aaron Neville" coverArt="ar-6633" albumCount="1"/>
</index>
<index name="B">
<artist id="5950" name="Bob Marley" coverArt="ar-5950" albumCount="8"/>
<artist id="5957" name="Bruce Dickinson" coverArt="ar-5957" albumCount="2"/>
</index>
</artists>
Xsd generated the following classes for serialization:
public partial class Response
{
private object itemField;
private ItemChoiceType itemElementNameField;
private ResponseStatus statusField;
private string versionField;
[System.Xml.Serialization.XmlChoiceIdentifierAttribute("ItemElementName")]
public object Item
{
get
{
return this.itemField;
}
set
{
this.itemField = value;
}
}
[System.Xml.Serialization.XmlIgnoreAttribute()]
public ItemChoiceType ItemElementName
{
get
{
return this.itemElementNameField;
}
set
{
this.itemElementNameField = value;
}
}
public ResponseStatus status
{
get
{
return this.statusField;
}
set
{
this.statusField = value;
}
}
public string version
{
get
{
return this.versionField;
}
set
{
this.versionField = value;
}
}
}
public partial class ArtistsID3
{
private List<IndexID3> indexField;
public ArtistsID3()
{
this.indexField = new List<IndexID3>();
}
public List<IndexID3> index
{
get
{
return this.indexField;
}
set
{
this.indexField = value;
}
}
}
public enum ItemChoiceType
{
/// <remarks/>
album,
/// <remarks/>
albumList,
--- snip ----
When I'm trying to deserialize into a Response-Object the field Item is always null and ItemElementName gets the first value from the enum ItemChoiceType but version and status are correctly set. The retrieved xml-output looks like expected (see sample).
What works though is deserializing into ArtistsID3 but then I loose the status.
Here's the code:
SubsonicApi api = new SubsonicApi();
var request = new RestRequest();
request.Resource = "getArtists.view";
request.AddParameter("v", "1.10.2");
request.AddParameter("c", "no name yet");
// Item always null!
// var response = api.Execute<Response>(request);
var response = api.Execute<ArtistsID3>(request);
public T Execute<T>(RestRequest request)
where T : new()
{
var client = new RestClient();
client.BaseUrl = new System.Uri(BaseUrl);
client.Authenticator = new HttpBasicAuthenticator(_accountSid, _secretKey);
var response = client.Execute<T>(request);
Console.WriteLine("RESPONSE-DATA: " + response.Content);
return response.Data;
}
I'd be glad if somebody could point me in the right direction as I think the right way should be accessing the data through an Response object. Really don't know how to debug this not expected behaviour.
try this
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
SubsonicResponse subsonicResponse = new SubsonicResponse()
{
status = "ok",
version = "1.10.1",
artists = new Artists()
{
ignoredArticles = "The El La Los Las Le Les",
indexes = new List<Index>() {
new Index() {
name = "A", artists = new List<Artist>() {
new Artist() { id = 5449, name = "A-Ha", converArt = "ar-5449", albumCount = 4},
new Artist() { id = 5221, name = "ABBA", converArt = "ar-5421", albumCount = 6},
new Artist() { id = 5432, name = "AC/DC", converArt = "ar-5432", albumCount = 15},
new Artist() { id = 6633, name = "Aaron Neville", converArt = "ar-5633", albumCount = 1}
}
},
new Index() {
name = "B", artists = new List<Artist>() {
new Artist() { id = 5950, name = "Bob Marley", converArt = "ar-5950", albumCount = 8},
new Artist() { id = 5957, name = "Bruce Dickinson", converArt = "ar-5957", albumCount = 2}
}
}
}
}
};
XmlSerializer serializer = new XmlSerializer(typeof(SubsonicResponse));
StreamWriter writer = new StreamWriter(FILENAME);
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("", "http://subsonic.org/restapi");
serializer.Serialize(writer, subsonicResponse, ns);
writer.Flush();
writer.Close();
writer.Dispose();
XmlSerializer xs = new XmlSerializer(typeof(SubsonicResponse));
XmlTextReader reader = new XmlTextReader(FILENAME);
SubsonicResponse newSResponse = (SubsonicResponse)xs.Deserialize(reader);
}
}
[XmlRoot("subsonic-response", Namespace = "http://subsonic.org/restapi")]
public class SubsonicResponse
{
[XmlAttribute("status")]
public string status { get; set; }
[XmlAttribute("version")]
public string version { get; set; }
[XmlElement("artists")]
public Artists artists { get; set; }
}
[XmlRoot(ElementName = "artists")]
public class Artists
{
[XmlAttribute("ignoredArticles")]
public string ignoredArticles { get; set; }
[XmlElement("index")]
public List<Index> indexes { get; set; }
}
[XmlRoot("index")]
public class Index
{
[XmlAttribute("name")]
public string name { get; set; }
[XmlElement("artist")]
public List<Artist> artists { get; set; }
}
[XmlRoot("artist")]
public class Artist
{
[XmlAttribute("id")]
public int id { get; set; }
[XmlAttribute("name")]
public string name { get; set; }
[XmlAttribute("converArt")]
public string converArt { get; set; }
[XmlAttribute("albumCount")]
public int albumCount { get; set; }
}
}
I am trying to create a function to parse an XML file like this:
<?xml version="1.0" encoding="utf-8"?>
<list name="Grocery List" author="Ian" desc="Saturday grocery list">
<item color="black" done="false">Milk</item>
<item color="black" done="false">Eggs</item>
<item color="blue" done="false">Water</item>
</list>
It parses the attributes correctly, but it fails to return the values of the list items. Here is the function and class it uses:
class List
{
public string[] listItems;
public string[] colorArray;
public string[] doneArray;
public string listName;
public string listAuthor;
public string listDesc;
public string err;
}
Reader definition:
class ListReader
{
public List doListParse(string filename)
{
List l = new List();
int arrayCount = 0;
try
{
XmlReader r = XmlReader.Create(filename);
while (r.Read())
{
if (r.NodeType == XmlNodeType.Element && r.Name == "list")
{
//Get the attributes of the list
l.listName = r.GetAttribute("name");
l.listAuthor = r.GetAttribute("author");
l.listDesc = r.GetAttribute("desc");
while (r.NodeType != XmlNodeType.EndElement)
{
r.Read();
if (r.Name == "item")
{
r.Read();
if (r.NodeType == XmlNodeType.Text)
{
//Get The Attributes
l.colorArray[arrayCount] = r.GetAttribute("color");
l.doneArray[arrayCount] = r.GetAttribute("done");
//Get The Content
l.listItems[arrayCount] = r.Value.ToString();
arrayCount++;
}
r.Read();
}
}
}
}
}
catch (Exception e)
{
l.err = e.ToString();
}
return l;
}
}
When I execute the program, it gives this exception:
System.NullReferenceException: Object reference not set to an instance of an object.
What is going on here?
I'd recommend you using a serializer. The XmlSerializer class is pretty decent. It will simplify your code.
So start by defining the models that will map to this XML structure:
[XmlRoot("list")]
public class GroceryList
{
[XmlAttribute("name")]
public string Name { get; set; }
[XmlAttribute("author")]
public string Author { get; set; }
[XmlAttribute("desc")]
public string Description { get; set; }
[XmlElement("item")]
public Item[] Items { get; set; }
}
public class Item
{
[XmlAttribute("color")]
public string Color { get; set; }
[XmlAttribute("done")]
public bool Done { get; set; }
[XmlText]
public string Value { get; set; }
}
and then simply deserialize the XML:
class Program
{
static void Main()
{
var serializer = new XmlSerializer(typeof(GroceryList));
using (var reader = XmlReader.Create("groceriesList.xml"))
{
var list = (GroceryList)serializer.Deserialize(reader);
// you could access the list items here
}
}
}
You can use Linq To Xml.
var xElem = XDocument.Parse(xml).Element("list"); //or XDocument.Load(filename)
var list = new
{
Name = xElem.Attribute("name").Value,
Author = xElem.Attribute("author").Value,
Desc = xElem.Attribute("desc").Value,
Items = xElem.Elements("item")
.Select(e => new{
Color = e.Attribute("color").Value,
Done = (bool)e.Attribute("done"),
Value = e.Value,
})
.ToList()
};