Given the following requirements and code, I have not yet found ONE answer that actually works.
I have an XML field in a SQL Server Database table. Why is it in there? I have no idea. I didn't put it in there. I just have to get the data out and into a List that I can combine with another List to populate a grid in a WPF app that has an MVVM architecture.
Here is that List:
List QAItems = new List();
The QADailyXValueCalCheck type is as follows:
using System.Xml.Serialization;
namespace ConvertXmlToList {
[XmlRoot(ElementName = "column")]
public class QADailyXValueCalCheck {
[XmlElement]
public string Regs { get; set; }
[XmlElement]
public string BasisTStamp { get; set; }
[XmlElement]
public string DAsWriteTStamp { get; set; }
[XmlElement]
public string InjEndTime { get; set; }
[XmlElement]
public bool Manual { get; set; }
[XmlElement]
public decimal RefValue { get; set; }
[XmlElement]
public decimal MeasValue { get; set; }
[XmlElement]
public string Online { get; set; }
[XmlElement]
public decimal AllowableDrift { get; set; }
[XmlElement]
public bool FailOoc { get; set; } = false;
[XmlElement]
public bool FailAbove { get; set; }
[XmlElement]
public bool FailBelow { get; set; }
[XmlElement]
public bool FailOoc5Day { get; set; }
[XmlElement]
public decimal InstSpan { get; set; }
[XmlElement]
public decimal GasLevel { get; set; }
[XmlElement]
public string CId { get; set; }
[XmlElement]
public string MId { get; set; }
[XmlElement]
public string CylinderId { get; set; }
[XmlElement]
public string CylinderExpDate { get; set; }
[XmlElement]
public string CylinderVendorId { get; set; }
[XmlElement]
public string CylinderGasTypeCode { get; set; }
}
}
The XML is being stored in a string, xmlString and comes out of the db in the following form:
<Regs>40CFR75</Regs>
<BasisTStamp>2016-02-15 05:18</BasisTStamp>
<DASWriteTStamp>2016-02-15 05:40</DASWriteTStamp>
<InjEndTime>2016-02-15 05:23</InjEndTime>
<Manual>0</Manual>
<RefValue>169.7</RefValue>
<MeasValue>169.27</MeasValue>
<Online>14</Online>
<AllowableDrift>15</AllowableDrift>
<FailAbove>0</FailAbove>
<FailBelow>0</FailBelow>
<InstSpan>300</InstSpan>
<GasLevel>MID</GasLevel>
<CID>111</CID>
<MID>N10</MID>
<CylinderID>CC357464</CylinderID>
<CylinderExpDate>2022-08-12</CylinderExpDate>
<CylinderVendorID>B22014</CylinderVendorID>
<CylinderGasTypeCode>BALN,SO2,NO,CO2</CylinderGasTypeCode>
Now, in order to get past the XML API's problem with "rootless" xml, I've added a root:
xmlString = "<columns>" + xmlString + "</columns>";
To parse this, I use:
XDocument doc = XDocument.Parse(xmlString);
Finally, to attempt to extract the VALUES from the XML and populate an instance of QADailyXValueCalCheck, I have the following code - which was adapted to work from other examples - THAT DO NOT WORK.
var xfields =
from r in doc.Elements("columns")
select new QADailyXValueCalCheck
{
Regs = (string) r.Element("Regs"),
BasisTStamp = (string) r.Element("BasisTStamp"),
DAsWriteTStamp = (string) r.Element("DASWriteTStamp"),
InjEndTime = (string) r.Element("InjEndTime"),
Manual = (bool) r.Element("Manual"),
RefValue = (decimal) r.Element("RefValue"),
MeasValue = (decimal)r.Element("MeasValue"),
Online = (string)r.Element("Online"),
AllowableDrift = (decimal)r.Element("AllowableDrift"),
//FailOoc = (bool)r.Element("FailOoc"),
//FailAbove = (bool)r.Element("FailAbove"),
//FailBelow = (bool)r.Element("FailBelow"),
//FailOoc5Day = (bool)r.Element("FailOoc5Day"),
//InstSpan = (decimal)r.Element("InstSpan"),
//GasLevel = (decimal)r.Element("GasLevel"),
CId = (string)r.Element("CID"),
MId = (string)r.Element("MID"),
CylinderId = (string)r.Element("CylinderId"),
CylinderExpDate = (string)r.Element("CylinderExpDate"),
CylinderVendorId = (string)r.Element("CylinderVendorId"),
CylinderGasTypeCode = (string)r.Element("CylinderGasTypeCode")
};
The code immediately above does NOT create a new instance of the class, "QADailyXValueCalCheck" which can be added to the List. I have a few null values that are causing a problem with that code, but that is a separate issue that I will deal with another time.
For now, can anyone tell me how that "var xfields = " query instantiates a new QADailyXValueCalCheck object that can be added to my List of the same type?
What code is missing? Thank you to the LINQ/XML genius that can answer this.
I had a similar question on XML parsing the other day from someone else here:
Create a List from XElements Dynamically
I think in the end you would be better served using a class with xml adornments and then have extension classes that serialize or deserialize the data. This makes it better IMHO in two ways:
1. You don't have to rewrite the parser and the POCO class, just the POCO class.
2. You can be free to reuse the extension method in other places.
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
namespace GenericTesting.Models
{
[XmlRoot(ElementName = "column")]
public class QADailyXValueCalCheck
{
[XmlElement]
public string Regs { get; set; }
[XmlElement]
public string BasisTStamp { get; set; }
[XmlElement]
public string DAsWriteTStamp { get; set; }
[XmlElement]
public string InjEndTime { get; set; }
[XmlElement]
public int Manual { get; set; }
[XmlElement]
public decimal RefValue { get; set; }
[XmlElement]
public decimal MeasValue { get; set; }
[XmlElement]
public int Online { get; set; }
[XmlElement]
public decimal AllowableDrift { get; set; }
[XmlElement]
public bool FailOoc { get; set; } = false;
[XmlElement]
public int FailAbove { get; set; }
[XmlElement]
public int FailBelow { get; set; }
[XmlElement]
public bool FailOoc5Day { get; set; }
[XmlElement]
public decimal InstSpan { get; set; }
[XmlElement]
public string GasLevel { get; set; }
[XmlElement]
public string CId { get; set; }
[XmlElement]
public string MId { get; set; }
[XmlElement]
public string CylinderId { get; set; }
[XmlElement]
public string CylinderExpDate { get; set; }
[XmlElement]
public string CylinderVendorId { get; set; }
[XmlElement]
public string CylinderGasTypeCode { get; set; }
}
}
And for the purpose of serializing/deserializing let me give extension methods for those:
using System.IO;
using System.Xml;
using System.Xml.Serialization;
namespace GenericTesting
{
static class ExtensionHelper
{
public static string SerializeToXml<T>(this T valueToSerialize)
{
dynamic ns = new XmlSerializerNamespaces();
ns.Add("", "");
StringWriter sw = new StringWriter();
using (XmlWriter writer = XmlWriter.Create(sw, new XmlWriterSettings { OmitXmlDeclaration = true }))
{
dynamic xmler = new XmlSerializer(valueToSerialize.GetType());
xmler.Serialize(writer, valueToSerialize, ns);
}
return sw.ToString();
}
public static T DeserializeXml<T>(this string xmlToDeserialize)
{
dynamic serializer = new XmlSerializer(typeof(T));
using (TextReader reader = new StringReader(xmlToDeserialize))
{
return (T)serializer.Deserialize(reader);
}
}
}
}
And a simple main entry point in a console app:
static void Main(string[] args)
{
var thingie = new QADailyXValueCalCheck
{
Regs = "40CFR75",
BasisTStamp = "2016-02-15 05:18",
DAsWriteTStamp = "2016-02-15 05:40",
InjEndTime = "2016-02-15 05:23",
Manual = 0, //Boolean This will probably mess up Changed to Int
RefValue = 169.7M,
MeasValue = 169.27M,
Online = 14, //Mismatch Type? Change to Int
AllowableDrift = 15,
FailAbove = 0, //Boolean This will probably mess up Changed to Int
FailBelow = 0, //Boolean This will probably mess up Changed to Int
InstSpan = 300,
GasLevel = "MID", //This is marked as a decimal? Changed to string
CId = "111",
MId = "N10",
CylinderId= "CC357464",
CylinderExpDate ="2022-08-12",
CylinderVendorId = "B22014",
CylinderGasTypeCode = "BALN,SO2,NO,CO2"
};
var serialized = thingie.SerializeToXml();
var deserialized = serialized.DeserializeXml<QADailyXValueCalCheck>();
Console.ReadLine();
}
This serializes just like this and I can get it back to deserialized as well.
Related
I am trying to deserialize XML and save the results to a database using entity framework.
The first section of code is just to get the needed xml file from an API.
Please see below:
public static void Main()
{
Program semoAPI = new Program();
using (WebClient webClient = new WebClient())
{
WebClient n = new WebClient();
//Bid Ask Curves
var bidAskCurves = n.DownloadString("https://reports.semopx.com/api/v1/documents/static-reports?" +
"page=1&page_size=1&order_by=ASC&ReportName=Bid/Ask%20Curves&Group=Market%20Data");
semoReports = JsonConvert.DeserializeObject<SemoReports>(bidAskCurves);
Console.WriteLine("Bid Ask Curves Report: ");
Console.WriteLine(semoReports.ResourceBaseUri + "/" + semoReports.Items[0].ResourceName);
string bidAskCurvesXML = semoReports.ResourceBaseUri + "/" + semoReports.Items[0].ResourceName;
XDocument bacDoc = XDocument.Load(bidAskCurvesXML);
//Execute DeserializeBidAskCurves
semoAPI.DeserializeBidAskCurves(bidAskCurvesXML);
}
}
Below is how my class is setup which contains the XML Elements I need:
namespace SEMO_app
{
[XmlRoot("BidAskCurves")]
public class BidAskCurves
{
[Key]
public int ReportID { get; set; }
[XmlElement("MarketArea")]
public MarketArea[] MarketAreas{ get; set; }
}
public class MarketArea
{
public string MarketAreaName { get; set; }
[XmlElement("DeliveryDay")]
public DeliveryDay[] DeliveryDays { get; set; }
}
public class DeliveryDay
{
public string Day { get; set; }
[XmlElement("TimeStep")]
public TimeStep[] TimeSteps{ get; set; }
}
public class TimeStep
{
public string TimeStepID { get; set; }
[XmlElement("Purchase")]
public Purchase[] Purchases { get; set; }
}
public class Purchase
{
public string Price { get; set; }
public string Volume { get; set; }
}
}
From here i would like to deserialize the XML and save the information to a database, below is the code I have so far which deserialize's the XML and gives the results back fine in the console.writesection.
However I am unable to save these values to the database table. The code complies and executes fine and a the database table updates, however the table only contains a report id column. Where I would like it to contain the items listed in the console.write section.
private void DeserializeBidAskCurves(string filename)
{
//Visual only not needed
Console.WriteLine("\n" + "Reading BidAskCurves XML File");
Console.WriteLine("===========================================================");
// Create an instance of the XmlSerializer.
XmlSerializer serializer = new XmlSerializer(typeof(BidAskCurves));
// Declare an object variable of the type to be deserialized.
BidAskCurves item;
using (XmlReader reader = XmlReader.Create(filename))
{
// Call the Deserialize method to restore the object's state.
item = (BidAskCurves)serializer.Deserialize(reader);
//Write out the properties of the object. (Visual Only, not needed)
Console.Write(
item.MarketAreas[0].MarketAreaName + "\t" +
item.MarketAreas[0].DeliveryDays[0].Day + "\t" +
item.MarketAreas[0].DeliveryDays[0].TimeSteps[0].TimeStepID + "\t" +
item.MarketAreas[0].DeliveryDays[0].TimeSteps[0].Purchases[0].Price + "\t" +
item.MarketAreas[0].DeliveryDays[0].TimeSteps[0].Purchases[0].Volume);
//write the properties to the db
using (SEMOContext context = new SEMOContext())
{
context.BidAskCurvesReports.Add(item);
context.SaveChanges();
}
}
}
Link to xml file: https://reports.semopx.com/documents/BidAskCurves_NI-IDA3_20190401_20190401161933.xml
Thanks for any help in advance.
Initially, it's hard to know what's the problem actually is?
But after visiting URI generated by
string bidAskCurvesXML = semoReports.ResourceBaseUri + "/" + semoReports.Items[0].ResourceName;
And that is https://reports.semopx.com/documents/BidAskCurves_NI-IDA3_20190401_20190401161933.xml
So, The class structure that you are using is different than xml generated by URI.
You need to use below class structure for your xml
[XmlRoot("Purchase")]
public class Purchase
{
[XmlElement("Price")]
public string Price { get; set; }
[XmlElement("Volume")]
public string Volume { get; set; }
}
[XmlRoot("Sell")]
public class Sell
{
[XmlElement("Price")]
public string Price { get; set; }
[XmlElement("Volume")]
public string Volume { get; set; }
}
[XmlRoot("TimeStep")]
public class TimeStep
{
[XmlElement("TimeStepID")]
public string TimeStepID { get; set; }
[XmlElement("Purchase")]
public List<Purchase> Purchase { get; set; }
[XmlElement("Sell")]
public List<Sell> Sell { get; set; }
}
[XmlRoot("DeliveryDay")]
public class DeliveryDay
{
[XmlElement("Day")]
public string Day { get; set; }
[XmlElement("TimeStep")]
public List<TimeStep> TimeStep { get; set; }
}
[XmlRoot("MarketArea")]
public class MarketArea
{
[XmlElement("MarketAreaName")]
public string MarketAreaName { get; set; }
[XmlElement("DeliveryDay")]
public DeliveryDay DeliveryDay { get; set; }
}
[XmlRoot("BidAskCurves")]
public class BidAskCurves
{
[XmlElement("MarketArea")]
public MarketArea MarketArea { get; set; }
}
And after using above class structure with XmlSerializer there are total 12 timestamp available
Usage:
XmlSerializer serializer = new XmlSerializer(typeof(BidAskCurves));
BidAskCurves item;
using (XmlReader reader = XmlReader.Create("https://reports.semopx.com/documents/BidAskCurves_NI-IDA3_20190401_20190401161933.xml"))
{
item = (BidAskCurves)serializer.Deserialize(reader);
//Your code to add above parsed data into database.
}
Output: (From Debugger)
Edit1:
To add first purchase's volume and price and sell's volume and price then,
...
item = (BidAskCurves)serializer.Deserialize(reader);
foreach (var ts in item.MarketArea.DeliveryDay.TimeStep)
{
BidAskCurvesData bidAskCurvesData = new BidAskCurvesData
{
ReportID = 123,
MarketAreaName = item.MarketArea.MarketAreaName,
Day = item.MarketArea.DeliveryDay.Day,
TimeSetID = ts.TimeStepID,
PurchasePrice = ts.Purchase[0].Price,
PurchaseVolume = ts.Purchase[0].Volume,
SellPrice = ts.Sell[0].Price,
SellVolume = ts.Sell[0].Volume
};
using (SEMOContext context = new SEMOContext())
{
context.BidAskCurvesReports.Add(item);
context.SaveChanges();
}
}
static void Main(string[] args)
{
using (WebClient webClient = new WebClient())
{
//Bid Ask Curves
var bidAskCurves = webClient.DownloadString("https://reports.semopx.com/documents/BidAskCurves_NI-IDA3_20190401_20190401161933.xml");
var serializer = new XmlSerializer(typeof(BidAskCurves));
BidAskCurves result;
using (TextReader reader = new StringReader(bidAskCurves))
{
// here it is
result = (BidAskCurves)serializer.Deserialize(reader);
}
}
Console.ReadKey();
}
and xml objects:
[XmlRoot(ElementName = "Purchase")]
public class Purchase
{
[XmlElement(ElementName = "Price")]
public string Price { get; set; }
[XmlElement(ElementName = "Volume")]
public string Volume { get; set; }
}
[XmlRoot(ElementName = "Sell")]
public class Sell
{
[XmlElement(ElementName = "Price")]
public string Price { get; set; }
[XmlElement(ElementName = "Volume")]
public string Volume { get; set; }
}
[XmlRoot(ElementName = "TimeStep")]
public class TimeStep
{
[XmlElement(ElementName = "TimeStepID")]
public string TimeStepID { get; set; }
[XmlElement(ElementName = "Purchase")]
public List<Purchase> Purchase { get; set; }
[XmlElement(ElementName = "Sell")]
public List<Sell> Sell { get; set; }
}
[XmlRoot(ElementName = "DeliveryDay")]
public class DeliveryDay
{
[XmlElement(ElementName = "Day")]
public string Day { get; set; }
[XmlElement(ElementName = "TimeStep")]
public List<TimeStep> TimeStep { get; set; }
}
[XmlRoot(ElementName = "MarketArea")]
public class MarketArea
{
[XmlElement(ElementName = "MarketAreaName")]
public string MarketAreaName { get; set; }
[XmlElement(ElementName = "DeliveryDay")]
public DeliveryDay DeliveryDays { get; set; }
}
[XmlRoot(ElementName = "BidAskCurves")]
public class BidAskCurves
{
[XmlElement(ElementName = "MarketArea")]
public MarketArea MarketAreas { get; set; }
}
EDIT
loop over the result:
foreach (var item in deliveryDays.TimeStep)
{
// var day = deliveryDays.Day
var timeStep_Purchase = item.Purchase;
var timeStep_Sell = item.Sell;
var timeStep_Id = item.TimeStepID;
}
I have the XML below:
<y:input xmlns:y='http://www.blahblah.com/engine/42'>
<y:datas>
<y:instance yclass='ReportPeriod' yid="report">
<language yid='en'/>
<threshold>0.6</threshold>
<typePeriod>predefinedPeriod</typePeriod>
<interval>month</interval>
<valuePeriod>April</valuePeriod>
<fund yclass="Fund">
<name>K</name>
<indexName>CAC40</indexName>
</fund>
</y:instance>
</y:datas>
</y:input>
That I am trying to deserialize to
[XmlRoot(ElementName="fund")]
public class Fund
{
[XmlElement(ElementName="name")]
public string Name { get; set; }
[XmlElement(ElementName="indexName")]
public string IndexName { get; set; }
[XmlAttribute(AttributeName="yclass")]
public string Yclass { get; set; }
}
[XmlRoot(ElementName="instance", Namespace="http://www.blahblah.com/engine/42")]
public class Instance
{
[XmlElement(ElementName="language")]
public Language Language { get; set; }
[XmlElement(ElementName="threshold")]
public string Threshold { get; set; }
[XmlElement(ElementName="typePeriod")]
public string TypePeriod { get; set; }
[XmlElement(ElementName="interval")]
public string Interval { get; set; }
[XmlElement(ElementName="valuePeriod")]
public string ValuePeriod { get; set; }
[XmlElement(ElementName="fund")]
public Fund Fund { get; set; }
[XmlAttribute(AttributeName="yclass")]
public string Yclass { get; set; }
[XmlAttribute(AttributeName="yid")]
public string Yid { get; set; }
}
[XmlRoot(ElementName="datas", Namespace="http://www.blahblah.com/engine/42")]
public class Datas
{
[XmlElement(ElementName="instance", Namespace="http://www.blahblah.com/engine/42")]
public Instance Instance { get; set; }
}
[XmlRoot(ElementName="input", Namespace="http://www.blahblah.com/engine/42")]
public class Input
{
[XmlElement(ElementName="datas", Namespace="http://www.blahblah.com/engine/42")]
public Datas Datas { get; set; }
[XmlAttribute(AttributeName="y", Namespace="http://www.blahblah.com/engine/42", Form = XmlSchemaForm.Qualified)]
public string Y { get; set; }
}
However, when deserializing the XML above:
public static class Program
{
public static void Main(params string[] args)
{
var serializer = new XmlSerializer(typeof(Input));
using (var stringReader = new StringReader(File.ReadAllText("file.xml")))
{
using(var xmlReader = XmlReader.Create(stringReader))
{
var instance = (Input)serializer.Deserialize(stringReader);
}
}
}
}
I get an error due to the y prefix...
There is an error in XML document (1, 1). ---> System.Xml.XmlException: Data at the root level is invalid. Line 1, position 1.
Reading some posts like that one: https://stackoverflow.com/a/36163079/4636721 it seems that there is maybe a bug with the XmlSerializer.
The cause of the exception is that you are passing stringReader rather than xmlReader to serializer.Deserialize(). You should be passing the XML reader instead:
Input instance = null;
var serializer = new XmlSerializer(typeof(Input));
using (var stringReader = new StreamReader("file.xml"))
{
using(var xmlReader = XmlReader.Create(stringReader))
{
instance = (Input)serializer.Deserialize(xmlReader);
}
}
(Apparently XmlReader.Create(stringReader) advances the text reader a bit, so if you later attempt to read from the stringReader directly, it has been moved past the root element.)
You also have some errors in your data model. It should look like:
[XmlRoot(ElementName="fund")]
public class Fund
{
[XmlElement(ElementName="name")]
public string Name { get; set; }
[XmlElement(ElementName="indexName")]
public string IndexName { get; set; }
[XmlAttribute(AttributeName="yclass")]
public string Yclass { get; set; }
}
[XmlRoot(ElementName="instance")]
[XmlType(Namespace = "")] // Add this
public class Instance
{
[XmlElement(ElementName="language")]
public Language Language { get; set; }
[XmlElement(ElementName="threshold")]
public string Threshold { get; set; }
[XmlElement(ElementName="typePeriod")]
public string TypePeriod { get; set; }
[XmlElement(ElementName="interval")]
public string Interval { get; set; }
[XmlElement(ElementName="valuePeriod")]
public string ValuePeriod { get; set; }
[XmlElement(ElementName="fund")]
public Fund Fund { get; set; }
[XmlAttribute(AttributeName="yclass")]
public string Yclass { get; set; }
[XmlAttribute(AttributeName="yid")]
public string Yid { get; set; }
}
[XmlRoot(ElementName="datas", Namespace="http://www.blahblah.com/engine/42")]
public class Datas
{
[XmlElement(ElementName="instance", Namespace="http://www.blahblah.com/engine/42")]
public Instance Instance { get; set; }
}
[XmlRoot(ElementName="input", Namespace="http://www.blahblah.com/engine/42")]
public class Input
{
[XmlElement(ElementName="datas", Namespace="http://www.blahblah.com/engine/42")]
public Datas Datas { get; set; }
//Remove This
//[XmlAttribute(AttributeName="y", Namespace="http://www.blahblah.com/engine/42", Form = XmlSchemaForm.Qualified)]
//public string Y { get; set; }
}
// Add this
[XmlRoot(ElementName="language")]
public class Language
{
[XmlAttribute(AttributeName="yid")]
public string Yid { get; set; }
}
Notes:
xmlns:y='http://www.blahblah.com/engine/42' is an XML namespace declaration and thus should not be mapped to a member in the data model.
The child elements of <y:instance ...> are not in any namespace. Unless the namespace of the child elements is specified by attributes somehow, XmlSerializer will assume that they should be in the same namespace as the containing element, here http://www.blahblah.com/engine/42".
Thus it is necessary to add [XmlType(Namespace = "")] to Instance to indicate the correct namespace for all child elements created from Instance. (Another option would be to add [XmlElement(Form = XmlSchemaForm.Unqualified)] to each member, but I think it is easier to set a single attribute on the type.)
A definition for Language is not included in your question, so I included one.
It will be more efficient to deserialize directly from your file using a StreamReader than to read first into a string, then deserialize from the string using a StringReader.
Working sample fiddle here.
I have EditText field and WebClient.
In EditText user write city.
EditText misto = FindViewById<EditText>(Resource.Id.misto) ;
TextView one = FindViewById<TextView>(Resource.Id.parentContainer);
TextView two = FindViewById<TextView>(Resource.Id.clicklistener1);
TextView three = FindViewById<TextView>(Resource.Id.clicklistener2);
TextView four = FindViewById<TextView>(Resource.Id.clicklistener3);
misto.TextChanged += (object sender, Android.Text.TextChangedEventArgs e) => {
var city = e.Text.ToString ();
};
I need to place text from EditText to xml string.
Code of POST request with xml
nadislati.Click += delegate
{
using (var client = new WebClient())
{
var values = new NameValueCollection();
values["Order"] = "<Order \n CallConfirm=\"1\"\n PayMethod=\"Безнал\" \n QtyPerson=\"2\" \n Type=\"2\" \n PayStateID=\"0\" \n Remark=\"тестовый заказ с мобильного приложения. просьба при получении заказа переслать скриншот на имейл ....#\" \n RemarkMoney=\"0\" \n TimePlan=\"\" \n Brand=\"1\" \n DiscountPercent=\"0\" \n BonusAmount=\"0\"\n Department=\"\"\n >\n <Customer Login=\"suhomlineugene#gmail.com\" FIO=\"Evgenyi Sukhomlin\"/>\n <Address \n CityName=\"\" \n StationName=\"\" \n StreetName=\"\" \n House=\"\" \n Corpus=\"\" \n Building=\"\" \n Flat=\"\" \n Porch=\"\" \n Floor=\"\" \n DoorCode=\"\"\n />\n\n <Phone Code=\" 096\" Number=\"50 526-43-19\" />\n <Products>\n <Product Code=\"574\" Qty=\"1\" />\n </Products>\n </Order>";
values["OrderText"] = "hello";
var response = client.UploadValues("http://193.203.48.54:5000/fastoperator.asmx/AddOrder", values);
var responseString = Encoding.UTF8.GetString(response);
}
Vibrator vib = (Vibrator)this.GetSystemService(Context.VibratorService);
vib.Vibrate(30);
var intent31 = new Intent(this, typeof(Cart3Activity));
StartActivity(intent31);
};
How I can realize this?
Normally you would have a data contract (a set of classes which represent the XML). You then populate this data contract with values. When you are done and want to send it as XML to the server, you take that object and serialize it into XML or JSON or whatever format the service requires. Taking the XML you have shown in the Order and throwing it through a XML 2 C# generator you get this:
using System;
using System.Xml.Serialization;
using System.Collections.Generic;
namespace Xml2CSharp
{
[XmlRoot(ElementName="Customer")]
public class Customer {
[XmlAttribute(AttributeName="Login")]
public string Login { get; set; }
[XmlAttribute(AttributeName="FIO")]
public string FIO { get; set; }
}
[XmlRoot(ElementName="Address")]
public class Address {
[XmlAttribute(AttributeName="CityName")]
public string CityName { get; set; }
[XmlAttribute(AttributeName="StationName")]
public string StationName { get; set; }
[XmlAttribute(AttributeName="StreetName")]
public string StreetName { get; set; }
[XmlAttribute(AttributeName="House")]
public string House { get; set; }
[XmlAttribute(AttributeName="Corpus")]
public string Corpus { get; set; }
[XmlAttribute(AttributeName="Building")]
public string Building { get; set; }
[XmlAttribute(AttributeName="Flat")]
public string Flat { get; set; }
[XmlAttribute(AttributeName="Porch")]
public string Porch { get; set; }
[XmlAttribute(AttributeName="Floor")]
public string Floor { get; set; }
[XmlAttribute(AttributeName="DoorCode")]
public string DoorCode { get; set; }
}
[XmlRoot(ElementName="Phone")]
public class Phone {
[XmlAttribute(AttributeName="Code")]
public string Code { get; set; }
[XmlAttribute(AttributeName="Number")]
public string Number { get; set; }
}
[XmlRoot(ElementName="Product")]
public class Product {
[XmlAttribute(AttributeName="Code")]
public string Code { get; set; }
[XmlAttribute(AttributeName="Qty")]
public string Qty { get; set; }
}
[XmlRoot(ElementName="Products")]
public class Products {
[XmlElement(ElementName="Product")]
public Product Product { get; set; }
}
[XmlRoot(ElementName="Order")]
public class Order {
[XmlElement(ElementName="Customer")]
public Customer Customer { get; set; }
[XmlElement(ElementName="Address")]
public Address Address { get; set; }
[XmlElement(ElementName="Phone")]
public Phone Phone { get; set; }
[XmlElement(ElementName="Products")]
public Products Products { get; set; }
[XmlAttribute(AttributeName="CallConfirm")]
public string CallConfirm { get; set; }
[XmlAttribute(AttributeName="PayMethod")]
public string PayMethod { get; set; }
[XmlAttribute(AttributeName="QtyPerson")]
public string QtyPerson { get; set; }
[XmlAttribute(AttributeName="Type")]
public string Type { get; set; }
[XmlAttribute(AttributeName="PayStateID")]
public string PayStateID { get; set; }
[XmlAttribute(AttributeName="Remark")]
public string Remark { get; set; }
[XmlAttribute(AttributeName="RemarkMoney")]
public string RemarkMoney { get; set; }
[XmlAttribute(AttributeName="TimePlan")]
public string TimePlan { get; set; }
[XmlAttribute(AttributeName="Brand")]
public string Brand { get; set; }
[XmlAttribute(AttributeName="DiscountPercent")]
public string DiscountPercent { get; set; }
[XmlAttribute(AttributeName="BonusAmount")]
public string BonusAmount { get; set; }
[XmlAttribute(AttributeName="Department")]
public string Department { get; set; }
}
}
You probably need to fix some of the types on some of the properties as the generator is not super clever about this.
Anyways, populate those properties with your values and when you want to create XML from it:
public static string SerializeObject<T>(this T toSerialize)
{
var xmlSerializer = new XmlSerializer(toSerialize.GetType());
using(var textWriter = new StringWriter())
{
xmlSerializer.Serialize(textWriter, toSerialize);
return textWriter.ToString();
}
}
var myXml = SerializeObject<Order>(order);
Where order is an instance of Order. myXml will be your XML string you can pass on to the server.
EDIT
Since you already have that XML string, you will need to deserialize it into the object, so you can manipulate it:
public static T DeserializeObject<T>(string xml)
{
using (var ms = new MemoryStream())
using (var writer = new StreamWriter(ms))
{
writer.Write(xml);
ms.Position = 0;
var serializer = new XmlSerializer(typeof(T));
using (var reader = XmlReader.Create(ms))
return (T)serializer.Deserialize(reader);
}
}
var order = DeserializeObject<Order>(xmlOrder);
Then you can manipulate order and when you are done, convert it back to XML with:
var myXml = SerializeObject<Order>(order);
You have to make sure your XML is well formed when you use these methods.
I have searched alot to find a solution, but couldn't come up with one after all.
So I hope that someone here can help me out.
I have an xml structure:
<?xml version="1.0" encoding="utf-8" ?>
<ReleaseNoteConfig>
<ReleaseNoteProperties>
<TemplateLocation>Path to the template location</TemplateLocation>
<TemplateFileName>wordfile.docx</TemplateFileName>
<OutLocation>Path to the outlocation</OutLocation>
<ReleaseName>Stackoverflow</ReleaseName>
<ChangeOrder>1234</ChangeOrder>
<ChangesHeader>Change ID</ChangesHeader>
<ProblemsHeader>Problem ID</ProblemsHeader>
<Environment>Test</Environment>
</ReleaseNoteProperties>
<DocProperties>
<AuthorReleaseNote>Vincent Verweij</AuthorReleaseNote>
<CustomerResponsible>Customer name</CustomerResponsible>
<PlannedTestInstallDate>-</PlannedTestInstallDate>
<PlannedAccInstallDate>30/04/2014</PlannedAccInstallDate>
<PlannedProdInstallDate>07/05/2014</PlannedProdInstallDate>
<TestInstallDate>-</TestInstallDate>
<AccInstallDate>-</AccInstallDate>
<ProdInstallDate>-</ProdInstallDate>
<TestInstaller>-</TestInstaller>
<AccInstaller>-</AccInstaller>
<ProdInstaller>-</ProdInstaller>
<UrlProjectPortal>Url to project site</UrlProjectPortal>
</DocProperties>
<SpecialProperties>
<Customer_x0020_Name>Customer company name</Customer_x0020_Name>
<Customer_x0020_Reference>No reference</Customer_x0020_Reference>
<Approval_x0020_Date>15/04/2014</Approval_x0020_Date>
<MyFerranti_x0020_Reference>1234</MyFerranti_x0020_Reference>
<Project_x0020_ID>Proj000001</Project_x0020_ID>
</SpecialProperties>
</ReleaseNoteConfig>
I have used an online generator to create a json from my XML and then json2csharp to obtain the classes that I need. So eventually it came up with this c# code:
public class ReleaseNoteProperties
{
public string TemplateLocation { get; set; }
public string TemplateFileName { get; set; }
public string OutLocation { get; set; }
public string ReleaseName { get; set; }
public string ChangeOrder { get; set; }
public string ChangesHeader { get; set; }
public string ProblemsHeader { get; set; }
public string Environment { get; set; }
}
public class DocProperties
{
public string AuthorReleaseNote { get; set; }
public string CustomerResponsible { get; set; }
public string PlannedTestInstallDate { get; set; }
public string PlannedAccInstallDate { get; set; }
public string PlannedProdInstallDate { get; set; }
public string TestInstallDate { get; set; }
public string AccInstallDate { get; set; }
public string ProdInstallDate { get; set; }
public string TestInstaller { get; set; }
public string AccInstaller { get; set; }
public string ProdInstaller { get; set; }
public string UrlProjectPortal { get; set; }
}
public class SpecialProperties
{
public string Customer_x0020_Name { get; set; }
public string Customer_x0020_Reference { get; set; }
public string Approval_x0020_Date { get; set; }
public string MyFerranti_x0020_Reference { get; set; }
public string Project_x0020_ID { get; set; }
}
public class ReleaseNoteConfig
{
public ReleaseNoteProperties ReleaseNoteProperties { get; set; }
public DocProperties DocProperties { get; set; }
public SpecialProperties SpecialProperties { get; set; }
}
This code will read my XML file and deserializes the XML to the objects.
public ReleaseNoteConfig ReadXmlToObject(string xmlPath)
{
StringReader stream = null;
XmlTextReader reader = null;
var xDocument = XDocument.Load(xmlPath);
string xml = xDocument.ToString();
try
{
// Serialise the object
XmlSerializer serializer = new XmlSerializer(typeof(ReleaseNoteConfig));
// Read the XML data
stream = new StringReader(xml);
// Create a reader
reader = new XmlTextReader(stream);
// Convert reader to an object
return (ReleaseNoteConfig)serializer.Deserialize(reader);
}
catch
{
return null;
}
finally
{
if (stream != null) stream.Close();
if (reader != null) reader.Close();
}
}
Now the problem; when I debug in Visual Studio, I see that two of the three objects are filled. Here is a screenshot that I took from the debugger:
http://www.smartus.be/xmlProblem/debugger.png
As you can see, DocProperties and ReleaseNoteProperties are filled correctly but SpecialProperties has all null values. First I thought it had something to do with the underscores, but when I added an underscore to a property in DocProperties it was also filled correctly.
I also tried adding the attributes above the properties like XmlElement, XmlRoot etc. but that didn't help either.
I also double checked for typos but it seems that there are none...
Hopefully you guys can help me out on this one.
Thanks in advance.
Vincent
Change your SpecialProperties class to this:
public class SpecialProperties
{
[XmlElement("Customer Name")]
public string CustomerName { get; set; }
[XmlElement("Customer Reference")]
public string CustomerReference { get; set; }
[XmlElement("Approval Date")]
public string ApprovalDate { get; set; }
[XmlElement("MyFerranti Reference")]
public string MyFerrantiReference { get; set; }
[XmlElement("Project ID")]
public string ProjectID { get; set; }
}
You can change the property names if you want, the important parts are the XmlElement attributes.
I have checked your code.
Can you Remove the underscores in the "Customer_x0020_Name" ? at the same time you need to change the property names in the class.
Its going to work.
Will this suggestions helps you?
i have checked it .. its working.
I am not sure , whether the tag name with underscore is legal or not.
Mark the answer , if it has solved you question
I know its a lot code... sorry for that....my list class is like this..
public class XMLList
{
public string Title { get; set; }
[DataMember]
public string Link { get; set; }
[DataMember]
public DateTime pubDate { get; set; }
[DataMember]
public string dcCreator { get; set; }
[DataMember]
public string GUID { get; set; }
[DataMember]
public Int32 wpPostId { get; set; }
[DataMember]
public string wpStatus { get; set; }
[DataMember]
public Int32 wpMenuOrd { get; set; }
[DataMember]
public string Category { get; set; }
[DataMember]
public List<Comment> Comments { get; set; }
}
public class Comment
{
[DataMember]
public Int32 wpCmtId { get; set; }
[DataMember]
public string wpCmtAuthor { get; set; }
[DataMember]
public string wpCmtAuthorEmail { get; set; }
[DataMember]
public string wpCmtAuthorURL { get; set; }
[DataMember]
public Int64 wpCmtAuthorIP { get; set; }
[DataMember]
public DateTime wpCmtAuthorDate { get; set; }
}
my c# code is like this
XmlDocument doc = new XmlDocument();
doc.Load(#"xml\willowcreekassociationblog.wordpress.xml");
//Get Channel Node
XmlNode channelNode = doc.SelectSingleNode("rss/channel");
if (channelNode != null)
{
//Add NameSpace
XmlNamespaceManager nameSpace = new XmlNamespaceManager(doc.NameTable);
nameSpace.AddNamespace("excerpt", "http://wordpress.org/export/1.2/excerpt/");
nameSpace.AddNamespace("content", "http://purl.org/rss/1.0/modules/content/");
nameSpace.AddNamespace("dc", "http://purl.org/dc/elements/1.1/");
nameSpace.AddNamespace("wfw", "http://wellformedweb.org/CommentAPI/");
nameSpace.AddNamespace("wp", "http://wordpress.org/export/1.2/");
//Parse each item
foreach (XmlNode itemNode in channelNode.SelectNodes("item"))
{
objrssItem.Add(rssItem);
rssItem.GUID = itemNode.SelectSingleNode("guid").InnerText;
rssItem.Title = itemNode.SelectSingleNode("title").InnerText;
rssItem.dcCreator = itemNode.SelectSingleNode("dc:creator", nameSpace).InnerText;
rssItem.Link = itemNode.SelectSingleNode("link").InnerText;
rssItem.pubDate = DateTime.Parse(itemNode.SelectSingleNode("pubDate").InnerText);
rssItem.ContentEncoded = itemNode.SelectSingleNode("content:encoded", nameSpace).InnerText;
XmlNode cNode = doc.SelectSingleNode("rss/channel/item");
foreach (XmlNode commentNode in cNode.SelectNodes("wp:comment", nameSpace))
{
//rssItem.Comments = Comments
rsscomment.wpCmtId = Convert.ToInt32(commentNode.SelectSingleNode("wp:comment_id", nameSpace).InnerText);
rsscomment.wpCmtAuthor = commentNode.SelectSingleNode("wp:comment_author", nameSpace).InnerText;
rsscomment.wpCmtContent = commentNode.SelectSingleNode("wp:comment_content", nameSpace).InnerText;
}
}
oXMLListResult.listOfXMLResult = objrssItem;
}
i have xml like enter link description here
when I am trying to read for each item in channel with xmlnode and its working fine. and each item has multiple comments which trying to achieve by using foreach inside foreach. But wp:comment foreach item its not working. What am i doing wrong? I did some google but no luck.
Thanks.
XmlNode cNode = doc.SelectSingleNode("rss/channel/item");
This is resetting your item enumeration to the beginning, which would cause every item to have identical comments.
EDIT:
I believe this is the easiest way to fix the problem I mentioned. By searching below the already selected node, you avoid the repetition. Note that cNode is no longer required.
foreach (XmlNode commentNode in itemNode.SelectNodes("wp:comment", nameSpace))