C# SQLXML Deserialization to Class or Object - c#

http://rtt.metroinfo.org.nz/RTT/Public/Utility/File.aspx?ContentType=SQLXML&Name=JPPlatform.xml
http://rtt.metroinfo.org.nz/RTT/Public/Utility/File.aspx?Name=JPRoutePositionET.xml&ContentType=SQLXML&PlatformTag=536
Both of those are my sample data which I am pulling down using HttpClient, I want to grab the attributes(?) such as PlatformTag, ETA and the like.
This is using Univeral Apps for Windows 10 mobile and Desktop. But I can't figure out what's going on to do it.
XDocument Document = XDocument.Parse(RESPONSE_CONSTANT);
var Stops = from Stop in Document.Descendants("Platform")
select new
{
Platformtag = (string)Stop.Attribute("PlatformTag"),
Platformno = (string)Stop.Attribute("PlatformNo")};
foreach (var item in Stops)
BusData.Text = item.Platformtag;
}
Is what I currently have, but nothing comes from it, it just sits there like it sees nothing, from here I don't know enough about XML Parsing to find a next step.
Note: Response_Constant contains data like this: http://rtt.metroinfo.org.nz/RTT/Public/Utility/File.aspx?Name=JPRoutePositionET.xml&ContentType=SQLXML&PlatformTag=536

Try following. Had to modify xml to replace ampersand.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.IO;
namespace ConsoleApplication14
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
string xml = File.ReadAllText(FILENAME);
xml = xml.Replace("&", "&");
StringReader sReader = new StringReader(xml);
XmlReaderSettings settings = new XmlReaderSettings();
settings.ConformanceLevel = ConformanceLevel.Fragment;
XmlReader reader = XmlReader.Create(sReader);
List<Platform> platforms = new List<Platform>();
while (!reader.EOF)
{
if (reader.Name != "Platform")
{
reader.ReadToFollowing("Platform");
}
if (!reader.EOF)
{
XElement platform = (XElement)XElement.ReadFrom(reader);
platforms.Add(new Platform()
{
tag = (int)platform.Attribute("PlatformTag"),
no = (int?)platform.Attribute("PlatformNo"),
name = (string)platform.Attribute("Name"),
bearingToRoad = (double?)platform.Attribute("BearingToRoad"),
roadName = (string)platform.Attribute("RoadName"),
lat = (double)platform.Element(platform.Name.Namespace + "Position").Attribute("Lat"),
_long = (double)platform.Element(platform.Name.Namespace + "Position").Attribute("Long")
});
}
}
}
}
public class Platform
{
public int tag { get; set; }
public int? no { get; set; }
public string name { get; set; }
public double? bearingToRoad { get; set; }
public string roadName { get; set; }
public double lat { get; set; }
public double _long { get; set; }
}
}

Related

Read xml attribute as object

I have the following simple XML file and I am tying to read the attribute code, using a C# .NET Core Console. I really appetite for any help.
<course type="IT" date="19.09.2019">
<line code="IT001"/>
</course>
UPDATE
I need the result as an object.
Use xml serialization to get a class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using System.Globalization;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
XmlReader reader = XmlReader.Create(FILENAME);
XmlSerializer serializer = new XmlSerializer(typeof(Course));
Course course = (Course)serializer.Deserialize(reader);
}
}
[XmlRoot("course")]
public class Course
{
[XmlAttribute("type")]
public string _type { get; set; }
public DateTime _date { get; set; }
[XmlAttribute("date")]
public string date {
get { return _date.ToString("dd.MM.yyyy"); }
set { _date = DateTime.ParseExact(value, "dd.MM.yyyy", System.Globalization.CultureInfo.InvariantCulture); }
}
private string _code { get; set; }
[XmlElement("line")]
public Line line
{
get { return new Line() { code = _code }; }
set { _code = value.code; }
}
}
[XmlRoot("line")]
public class Line
{
[XmlAttribute("code")]
public string code { get; set; }
}
}
Many ways to skin this cat. Here is a solution by making use of XPath
var xmlDoc = new XmlDocument();
xmlDoc.LoadXml("<course type=\"IT\" date=\"19.09.2019\"> <line code=\"IT001\"/></course>");
var attrVal = xmlDoc.SelectSingleNode("/course/line/#code").Value;
Console.WriteLine("Attribute 'code' value is " + attrVal);

JSON to C# array

I have a ASP.NET method that needs to pull up some currency rates.
protected void btnTest_Click(object sender, EventArgs e)
{
HttpWebRequest WebReq = (HttpWebRequest)WebRequest.Create(string.Format("https://api.fixer.io/latest?base=JPY&symbols=SGD"));
WebReq.Method = "GET";
HttpWebResponse WebResp = (HttpWebResponse)WebReq.GetResponse();
string jsonString;
using (Stream stream = WebResp.GetResponseStream())
{
StreamReader reader = new StreamReader(stream, System.Text.Encoding.UTF8);
jsonString = reader.ReadToEnd();
}
JavaScriptSerializer js = new JavaScriptSerializer();
Item[] rates = js.Deserialize<Item[]>(jsonString);
for (int i = 0; i < rates.Length; i++)
{
Item rate = new Item();
rate = (Item) (rates[i]);
Rates rb=(Rates) rate.r;
lblResult.Text = lblResult.Text + rb.SGD;
}
}
This is the Item.cs class
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace ClientConsultationSystem
{
public class Rates
{
public double SGD { get; set; }
}
public class Item
{
public string b { get; set; }
public string d { get; set; }
public Rates r { get; set; }
}
}
Not sure what i am doing wrong, but i got this error.
No parameterless constructor defined for type of 'ClientConsultationSystem.Item[]'.
You need to convert into a List instead of an Item[] because JavascriptSerializer deserializes into an IEnumerable.
I made some changes to your code:
JavaScriptSerializer js = new JavaScriptSerializer();
var rates = js.Deserialize<List<Item>>(jsonString);
for (int i = 0; i < rates.Count; i++)
{
Item rate = new Item();
rate = (Item)(rates[i]);
Rates rb = (Rates)rate.rates;
}
public class Item
{
public string #base { get; set; }
public string date { get; set; }
public Rates rates { get; set; }
}
While deserializing it is important to have the object closely match the source. The #base is needed since base is a reserved word.
What Evan said. In other words.. your code needs constructors like:
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace ClientConsultationSystem
{
public class Rates
{
public Rates() { } // optional constructor
public Double SGD { get; set; }
}
public class Item
{
public Item()
{
r = new Rates();
}
public String b { get; set; }
public string d { get; set; }
public Rates r { get; set; }
}
}
Thank you so much for the responses. I managed to get it working.
It's been a while since i starting programming the whole Intranet system for my company, so i am just relying on whatever knowledge i have from Java and what i did for my final year project to do programming.
protected void Page_Load(object sender, EventArgs e)
{
HttpWebRequest WebReq = (HttpWebRequest)WebRequest.Create(string.Format("https://api.fixer.io/latest?base=JPY&symbols=SGD"));
WebReq.Method = "GET";
HttpWebResponse WebResp = (HttpWebResponse)WebReq.GetResponse();
string json;
using (Stream stream = WebResp.GetResponseStream())
{
StreamReader reader = new StreamReader(stream, System.Text.Encoding.UTF8);
json = reader.ReadToEnd();
}
var rates = JsonConvert.DeserializeObject<Item>(json);
Item r = new Item();
r = (Item)(rates);
Rates rb = (Rates)r.rates;
lblResult.Text = lblResult.Text + "" + rb.SGD;
}
The Item class
public class Rates
{
public double SGD { get; set; }
}
public class Item
{
public Item()
{
rates = new Rates();
}
public string #base { get; set; }
public string date { get; set; }
public Rates rates { get; set; }
}
If there is any resources/books that can help me to build up my knowledge on JSON on C#, i would appreciate some sharing.
Once again, thank you very much from the bottom of my heart.

c# xml serialization add namespace to nodes

I have two class : Osoba, test
public class test
{
public string raz { get; set; }
public string dwa { get; set; }
}
public class Osoba
{
public test tehe { get; set; }
}
I also add namespaces to main root and seralize
Osoba ne = new Osoba();
test t1 = new praca2.test();
t1.dwa = "fgfg";
t1.raz = "dfdfdfdf";
ne.tehe = t1;
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("dfs", "http://schemas.microsoft.com/office/infopath/2003/dataFormSolution");
ns.Add("d", "http://schemas.microsoft.com/office/infopath/2009/WSSList/dataFields");
ns.Add("pc", "http://schemas.microsoft.com/office/infopath/2007/PartnerControls");
XmlSerializer xsSubmit = new XmlSerializer(typeof(Osoba));
var xml = #"D:\dupa1.xml";
using (var stream = new FileStream(xml, FileMode.Create))
{
using (XmlWriter writer = XmlWriter.Create(stream))
{
xsSubmit.Serialize(writer, ne,ns);
xml = stream.ToString(); // Your XML
}
}
I get
<?xml version="1.0" encoding="utf-8"?>
<Osoba xmlns:dfs="http://schemas.microsoft.com/office/infopath/2003/dataFormSolution"xmlns:pc="http://schemas.microsoft.com/office/infopath/2007/PartnerControls"xmlns:d="http://schemas.microsoft.com/office/infopath/2009/WSSList/dataFields">
<tehe>
<raz>dfdfdfdf</raz>
<dwa>fgfg</dwa>
</tehe>
</Osoba>
I want add to node namespaces examle:
...
<pc:tehe>
<dfs:raz>dfdfdfdf</dfs:raz>
<dfs:dwa>fgfg</dfs:dwa>
</pc:tehe>
How I can do it?
I try add class atribute which set namespace
[XmlRoot("Node", Namespace="http://flibble")]
but it bad idea
You're almost there you just need to modify your classes slightly:
public class test
{
[XmlElement(Namespace = "http://schemas.microsoft.com/office/infopath/2003/dataFormSolution")]
public string raz { get; set; }
[XmlElement(Namespace = "http://schemas.microsoft.com/office/infopath/2003/dataFormSolution")]
public string dwa { get; set; }
}
public class Osoba
{
[XmlElement(Namespace = "http://schemas.microsoft.com/office/infopath/2007/PartnerControls")]
public test tehe { get; set; }
}
Sample implementation copied mostly from yours:
class Program
{
static void Main(string[] args)
{
Osoba ne = new Osoba();
test t1 = new test();
t1.dwa = "fgfg";
t1.raz = "dfdfdfdf";
ne.tehe = t1;
XmlSerializer xsSubmit = new XmlSerializer(typeof(Osoba));
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("dfs", "http://schemas.microsoft.com/office/infopath/2003/dataFormSolution");
ns.Add("pc", "http://schemas.microsoft.com/office/infopath/2007/PartnerControls");
var xml = #"D:\dupa1.xml";
using (var stream = new FileStream(xml, FileMode.Create))
{
using (XmlTextWriter writer = new XmlTextWriter(stream, Encoding.UTF8))
{
xsSubmit.Serialize(writer, ne, ns);
}
}
}
}
You will get this XML:
<?xml version="1.0" encoding="utf-8"?>
<Osoba xmlns:dfs="http://schemas.microsoft.com/office/infopath/2003/dataFormSolution" xmlns:pc="http://schemas.microsoft.com/office/infopath/2007/PartnerControls">
<pc:tehe>
<dfs:raz>dfdfdfdf</dfs:raz>
<dfs:dwa>fgfg</dfs:dwa>
</pc:tehe>
</Osoba>
Hth...
Uisng xml linq :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication42
{
class Program
{
static void Main(string[] args)
{
string xmlHeader =
"<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
"<Osoba xmlns:dfs=\"http://schemas.microsoft.com/office/infopath/2003/dataFormSolution\"" +
" xmlns:pc=\"http://schemas.microsoft.com/office/infopath/2007/PartnerControls\"" +
" xmlns:d=\"http://schemas.microsoft.com/office/infopath/2009/WSSList/dataFields\">" +
"</Osoba>";
XDocument doc = XDocument.Parse(xmlHeader);
XElement osoba = doc.Root;
XNamespace dfsNs = osoba.GetNamespaceOfPrefix("dfs");
XNamespace pcNs = osoba.GetNamespaceOfPrefix("pc");
osoba.Add(new XElement(pcNs + "tehe", new object[] {
new XElement(dfsNs + "raz", "dfdfdfdf"),
new XElement(dfsNs + "dwa", "fgfg")
}));
}
}
}
I think you are new at C#.I suggest you to study C# basics, design patterns and repository pattern.For your requirement you can use below codes
public class Tehe
{
public string Raz { get; set; }
public string Dwa { get; set; }
}
public class TeheRepository
{
private System.Xml.Linq.XDocument xmlDatas;
public TeheRepository(string filePath)
{
xmlDatas = XDocument.Load(filePath);
}
public IEnumerable<Tehe> FindAll()
{
return xmlDatas.Elements().Elements().Select(tehe =>
{
Tehe t = new Tehe();
t.Dwa = tehe.Elements().ElementAt(1).Value;
t.Raz = tehe.Elements().ElementAt(0).Value;
return t;
});
}
}

System.IO.IOException: file used by another process when try to write to file

I searched over the internet and saw many questions about it, i tried many suggestion solutions, but nothing seems to work for me (maybe i am not implementing something right)
Here is my aspx.cs code:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Newtonsoft.Json;
public partial class Default : Page
{
static List<Member> memberList = new List<Member>();
static string fileName = #"C:\Users\Nir - PC\Desktop\public\gradesClient.json";
protected void Page_Load(object sender, EventArgs e)
{
if (File.Exists(fileName))
{
using (StreamReader re = new StreamReader(fileName))
{
JsonTextReader reader = new JsonTextReader(re);
JsonSerializer se = new JsonSerializer();
object parsedData = se.Deserialize(reader);
string json = JsonConvert.SerializeObject(parsedData);
Console.Write(json);
}
}
}
protected void addBtn_Click(object sender, EventArgs e)
{
memberList = JsonConvert.DeserializeObject<List<Member>>(File.ReadAllText(fileName));
Member member = new Member();
member.id = 4;
member.name = name.Value;
member.email = email.Value;
member.Date = date.Value;
member.Address = address.Value;
member.Country = country.Value;
member.Zip = zip.Value;
member.Grade = Int32.Parse(grade.Value);
member.Course = course.Value;
memberList.Add(member);
string json = JsonConvert.SerializeObject(memberList.ToArray());
File.WriteAllText(fileName, json);
}
}
public class Member
{
public int id { get; set; }
public string name { get; set; }
public string email { get; set; }
public string Date { get; set; }
public string Address { get; set; }
public string Country { get; set; }
public string Zip { get; set; }
public int Grade { get; set; }
public string Course { get; set; }
public Member()
{
}
}
the error happens when it reach to line File.WriteAllText(fileName, json);
Please help me to fix the problem,
Please provide example code.
Thanks

C# Json and HttpWebRequest

I used HttpWebRequest to get the content from a website.
The problem is that I got a response in json and I don't really know how to use, convert and implement that data in my program.
Current code:
namespace Web_Scraper
{
class Program
{
static void Main(string[] args)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://steamcommunity.com/market/priceoverview/?currency=3&appid=440&market_hash_name=Genuine%20Purity%20Fist");
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader stream = new StreamReader(response.GetResponseStream());
string final_response = stream.ReadToEnd();
Console.WriteLine("Genuine Purity Fist");
Console.WriteLine(final_response);
Console.ReadKey();
}
}
}
Response:
{"success":true,"lowest_price":"1,05\u20ac","volume":"26","median_price":"1,06\u20ac"}
json2csharp code:
public class RootObject
{
public bool success { get; set; }
public string lowest_price { get; set; }
public string volume { get; set; }
public string median_price { get; set; }
}
Hey you could downloade Json.NET and parse your json string like this:
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://steamcommunity.com/market/priceoverview/?currency=3&appid=440&market_hash_name=Genuine%20Purity%20Fist");
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader stream = new StreamReader(response.GetResponseStream());
var final_response = stream.ReadToEnd();
// Converts the unicode to string correctValue.
string correctValue = "Euro";
StringBuilder sb = new StringBuilder(final_response);
if (sb.ToString().Contains("\\u20ac"))
{
sb.Replace("\\u20ac", correctValue);
}
dynamic items = JObject.Parse(sb.ToString());
bool success = items.success;
string lowest = items.lowest_price;
string volume = items.volume;
string median = items.median_price;
// Create a test object of RootObject class and display it's values in cw.
RootObject r = new RootObject(success, lowest, volume, median);
Console.WriteLine("TEST OBJECT VALUES: Success: " + r.success + ", lPrice: " + r.lowest_price + ", vol: " + r.volume + ", mPrice: " + r.median_price + "\n");
// Calculation example
double num1 = Convert.ToDouble(r.FixComma(r.lowest_price,correctValue));
double num2 = Convert.ToDouble(r.FixComma(r.median_price, correctValue));
double result = num1 + num2;
Console.WriteLine("Result: " + result+"\n");
Console.WriteLine("Genuine Purity Fist");
Console.WriteLine(final_response);
Console.ReadKey();
}
}
public class RootObject
{
public bool success { get; set; }
public string lowest_price { get; set; }
public string volume { get; set; }
public string median_price { get; set; }
public RootObject(bool success, string lowest_price, string volume, string median_price)
{
this.success = success;
this.lowest_price = lowest_price;
this.volume = volume;
this.median_price = median_price;
}
public string FixComma(string value,string currency)
{
string correctValue = ".";
string correctValue2 = "";
StringBuilder sb = new StringBuilder(value);
if (sb.ToString().Contains(","))
{
sb.Replace(",", correctValue);
}
if (sb.ToString().Contains(currency))
{
sb.Replace(currency, correctValue2);
}
return sb.ToString();
}
}
}
Here is a link that explains how to downloade Json.NET https://www.nuget.org/packages/newtonsoft.json/.
One option is to use the JavaScriptSerializer class in the System.Web.Script.Serialization namespace.
For example:
RootObject obj = new JavaScriptSerializer().Deserialize<RootObject>(final_response);
Other options might be:
Do it yourself using reflection or manual parsing.
Third-party libraries like this one.
I would use JSON.NET for this. It provides a powerful and flexible way to deserialize and consume the data (and lets you change your mind about how to do it fairly easily later). It's also available as a NuGet package.
The simplest way would be to deserialize it into a dynamic or Object instance:
var object = JsonConvert.Deserialize<Object>(final_response);
var isSuccessful = object.success; // true or false
// ...
(You can replace object with dynamic too.)
If you want to deserialize to a class, create one:
class PriceData {
public bool success { get; set; }
public string lowest_price { get; set; }
public string volume { get; set; }
public string median_price { get; set; }
}
Then call .Deserialize<PriceData>(final_response) instead.
If you don't like lowercase-named or underscore-named variables (which is not the common style in C#), you can override the deserialization to specify which field to use for which C# property:
class PriceData {
[JsonProperty("success")]
public bool Success { get; set; }
[JsonProperty("lowest_price")]
public string LowestPrice { get; set; }
[JsonProperty("volume")]
public string Volume { get; set; }
[JsonProperty("median_price")]
public string MedianPrice { get; set; }
}

Categories

Resources