Deserialize Xml error<xmlns=''> was not expected [duplicate] - c#

This question already has answers here:
{"<user xmlns=''> was not expected.} Deserializing Twitter XML
(12 answers)
Closed 6 months ago.
I get this error when deserialize a Xml response from server:
There is an error in XML document (2, 2).
was not expected.
This is my response xml:
<?xml version="1.0" encoding="utf-8"?>
<RK7QueryResult ServerVersion="7.6.5.515" XmlVersion="248" NetName="RK7_TEST" Status="Ok" CMD="GetRefList" ErrorText="" DateTime="2022-08-11T09:44:22" WorkTime="156" Processed="1" ArrivalDateTime="2022-08-11T09:44:22">
<RK7RefList Count="154">
<RK7Reference RefName="ALIASES" Count="25" DataVersion="1681"/>
<RK7Reference RefName="ALIASLANGUAGES" Count="29" DataVersion="2117"/>
</RK7RefList>
</RK7QueryResult>
My Object:
[XmlRoot("RK7QueryResult")]
public class ReferenceResponse
{
[XmlElement("ServerVersion")]
public string ServerVersion { get; set; }
[XmlElement("XmlVersion")]
public int XmlVersion { get; set; }
[XmlElement("NetName")]
public string NetName { get; set; }
[XmlElement("CMD")]
public string CMD { get; set; }
[XmlElement("Status")]
public string Status { get; set; }
[XmlElement("ErrorText")]
public string ErrorText { get; set; }
[XmlElement("DateTime")]
public DateTime DateTime { get; set; }
[XmlElement("WorkTime")]
public int WorkTime { get; set; }
[XmlElement("Processed")]
public int Processed { get; set; }
[XmlElement("ArrivalDateTime")]
public DateTime ArrivalDateTime { get; set; }
[XmlArray("RK7RefList")]
public List<Reference> RK7RefList { get; set; }
}
[XmlRoot("RK7Reference")]
public class Reference
{
[XmlElement("RefName")]
public string RefName { get; set; }
[XmlElement("Count")]
public int Count { get; set; }
[XmlElement("DataVersion")]
public int DataVersion { get; set; }
}
And my deserialization:
XmlSerializer serializer = new XmlSerializer(typeof(string));
using (TextReader reader = new StringReader(response.Data))
{
var result = (ReferenceResponse)serializer.Deserialize(reader);
}
I have searched many solution in here and tried but it isn't work for me, Did my object was worng or something else? Sorry for my bad english.

You are initializing the serializer with "string" instead of the type you want to deserialize
XmlSerializer serializer = new XmlSerializer(typeof(ReferenceResponse));
and you should use [XmlAttribute] in your class for attributes.
This should work:
using System;
using System.Xml.Serialization;
using System.IO;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
var xml = #"<?xml version=""1.0"" encoding=""utf-8"" ?>
<RK7QueryResult ServerVersion=""7.6.5.515"" XmlVersion=""248"" NetName=""RK7_TEST"" Status=""Ok"" CMD=""GetRefList"" ErrorText="""" DateTime=""2022-08-11T09:44:22"" WorkTime=""156"" Processed=""1"" ArrivalDateTime=""2022-08-11T09:44:22"">
<RK7RefList Count=""154"">
<RK7Reference RefName=""ALIASES"" Count=""25"" DataVersion=""1681""/>
<RK7Reference RefName=""ALIASLANGUAGES"" Count=""29"" DataVersion=""2117""/>
</RK7RefList>
</RK7QueryResult>";
XmlSerializer serializer = new XmlSerializer(typeof(ReferenceResponse));
using (TextReader reader = new StringReader(xml))
{
var result = (ReferenceResponse)serializer.Deserialize(reader);
Console.WriteLine(result.ServerVersion);
Console.WriteLine(result.RK7RefList[0].RefName);
}
}
}
[XmlRoot("RK7QueryResult")]
public class ReferenceResponse
{
[XmlAttribute("ServerVersion")]
public string ServerVersion { get; set; }
[XmlAttribute("XmlVersion")]
public int XmlVersion { get; set; }
[XmlAttribute("NetName")]
public string NetName { get; set; }
[XmlAttribute("CMD")]
public string CMD { get; set; }
[XmlAttribute("Status")]
public string Status { get; set; }
[XmlAttribute("ErrorText")]
public string ErrorText { get; set; }
[XmlAttribute("DateTime")]
public DateTime DateTime { get; set; }
[XmlAttribute("WorkTime")]
public int WorkTime { get; set; }
[XmlAttribute("Processed")]
public int Processed { get; set; }
[XmlAttribute("ArrivalDateTime")]
public DateTime ArrivalDateTime { get; set; }
[XmlArray("RK7RefList")]
[XmlArrayItem("RK7Reference")]
public List<Reference> RK7RefList { get; set; }
}
[XmlRoot("RK7Reference")]
public class Reference
{
[XmlAttribute("RefName")]
public string RefName { get; set; }
[XmlAttribute("Count")]
public int Count { get; set; }
[XmlAttribute("DataVersion")]
public int DataVersion { get; set; }
}

Related

Getting a JsonSerializationException when trying to deserialize PlayerStats

I want to insert into my class data from JSON but I got a Newtonsoft.Json.JsonSerializationException.
My PlayerStats class is good, I think, and I don't know why it's not working.
I can download and print JSON to the console but my code stops working at the point when I try to deserialize. I tried to add settings to deserialize but it's still not working.
Here is my code:
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System;
using System.Net;
namespace DiscordBot
{
class Osu
{
public string _nickname;
private string _key = "key";
public class PlayerStats
{
[JsonProperty("user_id")]
public int UserId { get; set; }
[JsonProperty("username")]
public string UserName { get; set; }
[JsonProperty("count300")]
public int Count300 { get; set; }
[JsonProperty("count100")]
public int Count100 { get; set; }
[JsonProperty("count50")]
public int Count50 { get; set; }
[JsonProperty("playcount")]
public int PlayCount { get; set; }
[JsonProperty("ranked_score")]
public long RankedScore { get; set; }
[JsonProperty("total_score")]
public long TotalScore { get; set; }
[JsonProperty("pp_rank")]
public int PpRank { get; set; }
[JsonProperty("level")]
public double Level { get; set; }
[JsonProperty("pp_raw")]
public double RawPp { get; set; }
[JsonProperty("accuracy")]
public double Accuracy { get; set; }
[JsonProperty("count_rank_ss")]
public int CountRankSs { get; set; }
[JsonProperty("count_rank_ssh")]
public int CoundRankSsh { get; set; }
[JsonProperty("count_rank_s")]
public int CountRankS { get; set; }
[JsonProperty("count_rank_sh")]
public int CountRankSh { get; set; }
[JsonProperty("count_rank_a")]
public int CountRankA { get; set; }
[JsonProperty("country")]
public string Country { get; set; }
[JsonProperty("pp_country_rank")]
public int PpCountryRank { get; set; }
}
public PlayerStats GetUserStats()
{
string json = string.Empty;
var result = JsonConvert.DeserializeObject<PlayerStats>(json);
try
{
string url = #"https://osu.ppy.sh/api/get_user";
using (WebClient wc = new WebClient())
{
wc.QueryString.Add("k", _key);
wc.QueryString.Add("u", _nickname);
wc.QueryString.Add("m", "0");
json = wc.DownloadString(url);
Console.WriteLine(json);
result = JsonConvert.DeserializeObject<PlayerStats>(json);
return result;
}
}
catch (WebException ex)
{
Console.WriteLine("Osu Error: " + ex.Status);
}
return result;
}
}
}
JSON:
[
{
"user_id":"10415972"
,"username":"iGruby"
,"count300":"851431"
,"count100":"15449 6"
,"count50":"19825"
,"playcount":"7129"
,"ranked_score":"453511877"
,"total_score" :"2735863526"
,"pp_rank":"147461"
,"level":"74.5611"
,"pp_raw":"1642.73"
,"accuracy" :"94.46521759033203"
,"count_rank_ss":"13"
,"count_rank_ssh":"2"
,"count_rank_s":"3 6"
,"count_rank_sh":"13"
,"count_rank_a":"65"
,"country":"PL"
,"pp_country_rank":"77 20"
,"events":[]
}
]
Refer this Tested Answer from the file I have loaded your json and DeserializeObject check my model also and how I am DeserializeObject
namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
string data = File.ReadAllText("D://readjson.txt");
var obj = JsonConvert.DeserializeObject<List<RootObject>>(data);
}
}
public class RootObject
{
public string user_id { get; set; }
public string username { get; set; }
public string count300 { get; set; }
public string count100 { get; set; }
public string count50 { get; set; }
public string playcount { get; set; }
public string ranked_score { get; set; }
public string total_score { get; set; }
public string pp_rank { get; set; }
public string level { get; set; }
public string pp_raw { get; set; }
public string accuracy { get; set; }
public string count_rank_ss { get; set; }
public string count_rank_ssh { get; set; }
public string count_rank_s { get; set; }
public string count_rank_sh { get; set; }
public string count_rank_a { get; set; }
public string country { get; set; }
public string pp_country_rank { get; set; }
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public List<object> events { get; set; }
}
}
Pp_country_rank and count_rank_s contains a space. This is trying to be parsed to an integer.
"count_rank_s":"3 6"
,"count_rank_sh":"13"
,"count_rank_a":"65"
,"country":"PL"
,"pp_country_rank":"77 20"

Deserializing XML, where the root object is an array returns only a single element

I have an XML document that I am working with, which I am trying to deserialize into a class. Here are the classes I have been working with:
[Serializable()]
[XmlRoot("list")]
public class ItemRoot
{
public ItemRoot()
{
Items = new List<Item>();
}
[XmlElement("itemDefinition")]
public List<Item> Items { get; set; }
}
[Serializable()]
public class Item
{
[System.Xml.Serialization.XmlElement("id")]
public int Id { get; set; }
[System.Xml.Serialization.XmlElement("name")]
public string Name { get; set; }
[System.Xml.Serialization.XmlElement("examine")]
public string Examine { get; set; }
[System.Xml.Serialization.XmlElement("equipmentType")]
public string EquipmentType { get; set; }
[System.Xml.Serialization.XmlElement("noted")]
public bool Noted { get; set; }
[System.Xml.Serialization.XmlElement("noteable")]
public bool Noteable { get; set; }
[System.Xml.Serialization.XmlElement("stackable")]
public bool Stackable { get; set; }
[System.Xml.Serialization.XmlElement("parentId")]
public int ParentId { get; set; }
[System.Xml.Serialization.XmlElement("notedId")]
public int NotedId { get; set; }
[System.Xml.Serialization.XmlElement("members")]
public bool Members { get; set; }
[System.Xml.Serialization.XmlElement("specialStorePrice")]
public int SpecialStorePrice { get; set; }
[System.Xml.Serialization.XmlElement("generalStorePrice")]
public int GeneralStorePrice { get; set; }
[System.Xml.Serialization.XmlElement("highAlcValue")]
public int HighAlcValue { get; set; }
[System.Xml.Serialization.XmlElement("lowAlcValue")]
public int LowAlcValue { get; set; }
[System.Xml.Serialization.XmlElement("bonus")]
public List<int> Bonus { get; set; }
public override string ToString()
{
return $"[{Id}]{Name}";
}
}
And here's a short excerpt of the XML file, containing one item in the array (the real file I use has more than one, just to be clear):
<list>
<itemDefinition>
<id>0</id>
<name>Stack Overflow</name>
<examine>Add coffee.</examine>
<equipmentType>NONE</equipmentType>
<noted>false</noted>
<noteable>false</noteable>
<stackable>false</stackable>
<parentId>-1</parentId>
<notedId>-1</notedId>
<members>true</members>
<specialStorePrice>0</specialStorePrice>
<generalStorePrice>0</generalStorePrice>
<highAlcValue>0</highAlcValue>
<lowAlcValue>0</lowAlcValue>
<bonus>
<int>0</int>
<int>0</int>
<int>0</int>
<int>0</int>
<int>0</int>
<int>0</int>
<int>0</int>
<int>0</int>
<int>0</int>
<int>0</int>
<int>0</int>
<int>0</int>
</bonus>
</itemDefinition>
And here is my deserialization method:
XmlSerializer reader = new XmlSerializer(typeof(ItemRoot));
_file.Position = 0;
object file = reader.Deserialize(_file);
Root = (ItemRoot)file;
_file.Close();
I have tried looking into similar questions, however using those solutions yielded no results.
If i understand you correctly, you have XML with multiple itemDefinition sections and you want to deserialize that to a List of itemDefinition(s)....
Try this
Usings.....
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
Classes.....
[XmlRoot(ElementName = "bonus")]
public class Bonus
{
[XmlElement(ElementName = "int")]
public List<string> Int { get; set; }
}
[XmlRoot(ElementName = "itemDefinition")]
public class ItemDefinition
{
[XmlElement(ElementName = "id")]
public string Id { get; set; }
[XmlElement(ElementName = "name")]
public string Name { get; set; }
[XmlElement(ElementName = "examine")]
public string Examine { get; set; }
[XmlElement(ElementName = "equipmentType")]
public string EquipmentType { get; set; }
[XmlElement(ElementName = "noted")]
public string Noted { get; set; }
[XmlElement(ElementName = "noteable")]
public string Noteable { get; set; }
[XmlElement(ElementName = "stackable")]
public string Stackable { get; set; }
[XmlElement(ElementName = "parentId")]
public string ParentId { get; set; }
[XmlElement(ElementName = "notedId")]
public string NotedId { get; set; }
[XmlElement(ElementName = "members")]
public string Members { get; set; }
[XmlElement(ElementName = "specialStorePrice")]
public string SpecialStorePrice { get; set; }
[XmlElement(ElementName = "generalStorePrice")]
public string GeneralStorePrice { get; set; }
[XmlElement(ElementName = "highAlcValue")]
public string HighAlcValue { get; set; }
[XmlElement(ElementName = "lowAlcValue")]
public string LowAlcValue { get; set; }
[XmlElement(ElementName = "bonus")]
public Bonus Bonus { get; set; }
}
[XmlRoot(ElementName = "list")]
public class List
{
[XmlElement(ElementName = "itemDefinition")]
public List<ItemDefinition> ItemDefinition { get; set; }
}
code.....
static void Main(string[] args)
{
string strXML = File.ReadAllText("xml.xml");
byte[] bufXML = ASCIIEncoding.UTF8.GetBytes(strXML);
MemoryStream ms1 = new MemoryStream(bufXML);
// Deserialize to object
XmlSerializer serializer = new XmlSerializer(typeof(List));
try
{
using (XmlReader reader = new XmlTextReader(ms1))
{
List deserializedXML = (List)serializer.Deserialize(reader);
}// put a break point here and mouse-over deserializedXML….
}
catch (Exception ex)
{
throw;
}
}
I saved\read your XML from a file called xml.xml in the application build folder.....
You need to add an Items node underneath the list element, and then put the item nodes underneath it. If you cannot change the xml then try serializing as an array or list directly instead of as an object that contains a list.

Deserialize Fails to populate elements in the object

I have a few questions about deserializing an xml file into an object that has been bothering me for almost two days. I appreciate any help anyone can offer!
I used xsd.exe to generate c# classes from the schema files. I then used XMLExplorer to create a sample XML file. Is it a correct assumption that if I save that sample file, unchanged, with the sample text values, and deserialize it into the appropriate c# class, that it "should" read the values and put them into the appropriate objects???
Does the XMLDeserializer REQUIRE that all elements be present in the XML file or can an XML file contain missing elements and still be deserialized correctly (by, for instance, putting null values in missing properties)???
I've read that XMLSerializer only checks for three errors and I've got those resolved by tagging the xmlroot and removing a broken URL. My code runs, but I'm getting nulls for "InvokingBusinessActivity" and "Passenger" and other properties.
Here's my deserialization code.
IATA_PassengerConformanceIdentifyRQ localIataReq = new IATA_PassengerConformanceIdentifyRQ();
XmlSerializer deserializer = new XmlSerializer(localIataReq.GetType());
StreamReader reader = new StreamReader("C:\\Airports\\Projects_Current\\Multi-channel\\Dev\\Integration\\MCUniversalBagDropAPITester\\IataXmlSchemas\\Test Xml Files\\PassengerIdentifyRequest.xml");
XmlRootAttribute xRoot = new XmlRootAttribute();
xRoot.ElementName = "IATA_PassengerConformanceIdentifyRQ";
xRoot.IsNullable = false;
localIataReq = (IATA_PassengerConformanceIdentifyRQ)deserializer.Deserialize(reader);
reader.Close();
here's my class that was generate from XSD. This is trimmed down because it is about 1000 lines:
using System.Xml.Serialization;
//
// This source code was auto-generated by xsd, Version=4.0.30319.1.
//
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.1")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true, Namespace="http://www.iata.org/IATA/2007/00")]
[System.Xml.Serialization.XmlRootAttribute("IATA_PassengerConformanceIdentifyRQ", IsNullable = false)] /* I commented out and obfuscated defective Namespace="http://ww w.iat a.org/IATA/2007/00",*/
public partial class IATA_PassengerConformanceIdentifyRQ
{
private SourceType[] originatorField;
private BusinessActivityType invokingBusinessActivityField;
private IATA_PassengerConformanceIdentifyRQPassenger passengerField;
private string echoTokenField;
private System.DateTime timeStampField;
private bool timeStampFieldSpecified;
private IATA_PassengerConformanceIdentifyRQTarget targetField;
private decimal versionField;
private string transactionIdentifierField;
private string sequenceNmbrField;
private IATA_PassengerConformanceIdentifyRQTransactionStatusCode transactionStatusCodeField;
private bool transactionStatusCodeFieldSpecified;
private bool retransmissionIndicatorField;
private bool retransmissionIndicatorFieldSpecified;
private string correlationIDField;
private bool asynchronousAllowedIndField;
private bool asynchronousAllowedIndFieldSpecified;
public IATA_PassengerConformanceIdentifyRQ() {
this.targetField = IATA_PassengerConformanceIdentifyRQTarget.Production;
}
/// <remarks/>
[System.Xml.Serialization.XmlArrayItemAttribute("Source", IsNullable=false)]
public SourceType[] Originator {
get {
return this.originatorField;
}
set {
this.originatorField = value;
}
}
/// <remarks/>
public BusinessActivityType InvokingBusinessActivity {
get {
return this.invokingBusinessActivityField;
}
set {
this.invokingBusinessActivityField = value;
}
}
ETC......
Here's the test file that was created by VS2010 XMLSchema Explorer. For simplicity, duplicate elements of "complex type" were removed. The broken URL was also removed and I added the xml version to the top to fix serialization issues.
<?xml version="1.0" encoding="utf-8"?>
<IATA_PassengerConformanceIdentifyRQ>
<!-- EchoToken="EchoToken1" TimeStamp="1900-01-01T01:01:01-06:00" Target="Production" Version="1" TransactionIdentifier="TransactionIdentifier1" SequenceNmbr="32" TransactionStatusCode="Start" PrimaryLangID="en" AltLangID="en" RetransmissionIndicator="true" CorrelationID="CorrelationID1" AsynchronousAllowedInd="true" xmlns="ht tp: // www . iata.org/IATA/2007/00" -->
<Originator>
<Source AgentSine="AgentSine1" PseudoCityCode="PseudoCityCode1" ISOCountry="ISOCountry1" ISOCurrency="ISOCurrency1" AgentDutyCode="AgentDutyCode1" AirlineVendorID="AirlineVendorID1" AirportCode="AirportCode1" FirstDepartPoint="Fi1" ERSP_UserID="ERSP_UserID1" TerminalID="TerminalID1">
<RequestorID MessagePassword="MessagePassword1" URL="http://uri1" Type="Type1" Instance="Instance1" ID="ID1" ID_Context="ID_Context1">
<CompanyName CompanyShortName="CompanyShortName1" TravelSector="TravelSector1" Code="Code1" CodeContext="CodeContext1">CompanyName1</CompanyName>
</RequestorID>
<Position Latitude="Latitude1" Longitude="Longitude1" Altitude="Altitude1" AltitudeUnitOfMeasureCode="AltitudeUnitOfMeasureCode1" />
<BookingChannel Type="Type1" Primary="true">
<CompanyName CompanyShortName="CompanyShortName1" TravelSector="TravelSector1" Code="Code1" CodeContext="CodeContext1">CompanyName1</CompanyName>
</BookingChannel>
</Source>
</Originator>
<InvokingBusinessActivity Code="06">Baggage Processing</InvokingBusinessActivity>
<Passenger>
<GUID>GUID1</GUID>
<NativeID>NativeID1</NativeID>
<Name ShareSynchInd="Yes" ShareMarketInd="Yes" NameType="NameType1">
<NamePrefix>NamePrefix1</NamePrefix>
<NamePrefix>NamePrefix2</NamePrefix>
<NamePrefix>NamePrefix3</NamePrefix>
<GivenName>GivenName1</GivenName>
<GivenName>GivenName2</GivenName>
<GivenName>GivenName3</GivenName>
<MiddleName>MiddleName1</MiddleName>
<MiddleName>MiddleName2</MiddleName>
<MiddleName>MiddleName3</MiddleName>
<SurnamePrefix>SurnamePrefix1</SurnamePrefix>
<Surname>Surname1</Surname>
<NameSuffix>NameSuffix1</NameSuffix>
<NameSuffix>NameSuffix2</NameSuffix>
<NameSuffix>NameSuffix3</NameSuffix>
<NameTitle>NameTitle1</NameTitle>
<NameTitle>NameTitle2</NameTitle>
<NameTitle>NameTitle3</NameTitle>
</Name>
<CustomerLoyalty ShareSynchInd="Yes" ShareMarketInd="Yes" ProgramID="ProgramID1" MembershipID="MembershipID1" TravelSector="TravelSector1" LoyalLevel="LoyalLevel1" SingleVendorInd="SingleVndr" SignupDate="1900-01-01" EffectiveDate="1900-01-01" ExpireDate="1900-01-01" RPH="RPH1" VendorCode="VendorC1 VendorC2 VendorC3 " />
<CustomerLoyalty ShareSynchInd="No" ShareMarketInd="No" ProgramID="ProgramID2" MembershipID="MembershipID2" TravelSector="TravelSector2" LoyalLevel="LoyalLevel2" SingleVendorInd="Alliance" SignupDate="0001-01-01" EffectiveDate="0001-01-01" ExpireDate="0001-01-01" RPH="RPH2" VendorCode="VendorC4 VendorC5 VendorC6 " />
<BoardingPass>
<ForIndividualAirlineUse>ForIndividualAirlineUse1</ForIndividualAirlineUse>
<DigitalSignature Type="1">DigitalSignature1</DigitalSignature>
</BoardingPass>
<Segment>
<PNR URL="http://uri1" Type="Type1" Instance="Instance1" ID="ID1" ID_Context="ID_Context1" />
<NativeID>NativeID1</NativeID>
<Flight>
<NativeID>NativeID1</NativeID>
<OperatingCarrier>Op1</OperatingCarrier>
<FlightNumber>FlightNumber1</FlightNumber>
<OperationalSuffix>OperationalSuffix1</OperationalSuffix>
<MarketingCarrier>Ma1</MarketingCarrier>
<ScheduledDateOfDeparture>1900-01-01</ScheduledDateOfDeparture>
<ScheduledTimeOfDeparture>01:01:01</ScheduledTimeOfDeparture>
<ScheduledDateOfArrival>1900-01-01</ScheduledDateOfArrival>
<ScheduledTimeOfArrival>01:01:01</ScheduledTimeOfArrival>
</Flight>
<DepartureAirport>
<AirportCode>Air1</AirportCode>
<SourceIndicator>1</SourceIndicator>
</DepartureAirport>
<ArrivalAirport>
<AirportCode>Air1</AirportCode>
<SourceIndicator>1</SourceIndicator>
</ArrivalAirport>
<Cabin>Cabin1</Cabin>
<SeatNumber>SeatNumber1</SeatNumber>
<CheckInSequenceNumber>Chec1</CheckInSequenceNumber>
</Segment>
</Passenger>
</IATA_PassengerConformanceIdentifyRQ>
I'm doing something wrong and I'm not certain exactly what!!! Can someone please advise???
Try code below. I did some spot checking for errors, but there still may be some issue. I read XML from a different filename so you need to go back to your original filename.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
IATA_PassengerConformanceIdentifyRQ localIataReq = new IATA_PassengerConformanceIdentifyRQ();
XmlSerializer deserializer = new XmlSerializer(localIataReq.GetType());
StreamReader reader = new StreamReader(FILENAME);
XmlRootAttribute xRoot = new XmlRootAttribute();
xRoot.ElementName = "IATA_PassengerConformanceIdentifyRQ";
xRoot.IsNullable = false;
localIataReq = (IATA_PassengerConformanceIdentifyRQ)deserializer.Deserialize(reader);
reader.Close();
XmlSerializer serializer = new XmlSerializer(typeof(IATA_PassengerConformanceIdentifyRQ));
StreamWriter writer = new StreamWriter(#"c:\temp\test1.xml");
serializer.Serialize(writer, localIataReq);
writer.Flush();
writer.Close();
writer.Dispose();
}
}
[XmlRoot("IATA_PassengerConformanceIdentifyRQ")]
public partial class IATA_PassengerConformanceIdentifyRQ
{
[XmlElement("Originator")]
public Originator originator { get; set;}
[XmlElement("InvokingBusinessActivity")]
public InvokingBusinessActivity invokingBusinessActivity { get; set; }
[XmlElement("Passenger")]
public Passenger passenger { get; set; }
}
[XmlRoot("Originator")]
public partial class Originator
{
[XmlElement("Source")]
public Source source { get; set;}
}
[XmlRoot("Source")]
public class Source
{
[XmlAttribute("AgentSine")]
public string agentSine { get; set; }
[XmlAttribute("PseudoCityCode")]
public string pseudoCityCode { get; set; }
[XmlAttribute("ISOCountry")]
public string iSOCountry { get; set; }
[XmlAttribute("ISOCurrency")]
public string iSOCurrency { get; set; }
[XmlAttribute("AgentDutyCode")]
public string agentDutyCode { get; set; }
[XmlAttribute("AirlineVendorID")]
public string airlineVendorID { get; set; }
[XmlAttribute("AirportCode")]
public string airportCode { get; set; }
[XmlAttribute("FirstDepartPoint")]
public string firstDepartPoint { get; set; }
[XmlAttribute("ERSP_UserID")]
public string eRSP_UserID { get; set; }
[XmlAttribute("TerminalID")]
public string terminalID { get; set; }
[XmlElement("RequestorID")]
public RequestorID requestorID { get; set; }
[XmlElement("Position")]
public Position position { get; set; }
[XmlElement("BookingChannel")]
public BookingChannel bookingChannel { get; set; }
}
[XmlRoot("RequestorID")]
public class RequestorID
{
[XmlAttribute("MessagePassword")]
public string messagePassword { get; set; }
[XmlAttribute("URL")]
public string url { get; set; }
[XmlAttribute("Type")]
public string _type { get; set; }
[XmlAttribute("Instance")]
public string instance { get; set; }
[XmlAttribute("ID")]
public string id { get; set; }
[XmlAttribute("ID_Context")]
public string id_Context { get; set; }
}
[XmlRoot("Position")]
public partial class Position
{
[XmlAttribute("Latitude")]
public string latitude { get; set; }
[XmlAttribute("Longitude")]
public string longitude { get; set; }
[XmlAttribute("Altitude")]
public string altitude { get; set; }
[XmlAttribute("AltitudeUnitOfMeasureCode")]
public string altitudeUnitOfMeasureCode { get; set; }
}
[XmlRoot("BookingChannel")]
public class BookingChannel
{
[XmlAttribute("Type")]
public string _type { get; set; }
[XmlAttribute("Primary")]
public Boolean primary { get; set; }
[XmlElement("CompanyName")]
public CompanyName companyName { get; set; }
}
[XmlRoot("CompanyName")]
public class CompanyName
{
[XmlAttribute("CompanyShortName")]
public string companyShortName { get; set; }
[XmlAttribute("TravelSector")]
public string travelSector { get; set; }
[XmlAttribute("Code")]
public string code { get; set; }
[XmlAttribute("CodeContext")]
public string codeContext { get; set; }
[XmlText]
public string name { get; set; }
}
[XmlRoot("InvokingBusinessActivity")]
public class InvokingBusinessActivity
{
[XmlAttribute("Code")]
public string code { get; set; }
[XmlText]
public string value { get; set; }
}
[XmlRoot("Passenger")]
public class Passenger
{
[XmlElement("GUID")]
public Value guid { get; set; }
[XmlElement("NativeID")]
public Value nativeID { get; set; }
[XmlElement("Name")]
public Name name { get; set; }
[XmlElement("CustomerLoyalty")]
public List<CustomerLoyalty> customerLoyalty { get; set; }
[XmlElement("BoardingPass")]
public BoardingPass boardingPass { get; set; }
[XmlElement("Segment")]
public Segment segment { get; set; }
}
public class Value
{
[XmlText]
public string value { get; set; }
}
[XmlRoot("Name")]
public class Name
{
[XmlAttribute("ShareSynchInd")]
public string shareSynchInd { get; set; }
[XmlAttribute("ShareMarketInd")]
public string shareMarketInd { get; set; }
[XmlAttribute("NameType")]
public string NameType { get; set; }
[XmlElement("NamePrefix")]
public List<string> namePrefix { get; set; }
[XmlElement("GivenName")]
public List<string> givenName { get; set; }
[XmlElement("MiddleName")]
public List<string> middleName { get; set; }
[XmlElement("SurnamePrefix")]
public List<string> surnamePrefix { get; set; }
[XmlElement("Surname")]
public List<string> surname { get; set; }
[XmlElement("NameSuffix")]
public string nameSuffix { get; set; }
[XmlElement("NameTitle")]
public string nameTitle { get; set; }
}
[XmlRoot("CustomerLoyalty")]
public class CustomerLoyalty
{
[XmlAttribute("ShareSynchInd")]
public string shareSynchInd { get; set; }
[XmlAttribute("ShareMarketInd")]
public string shareMarketInd { get; set; }
[XmlAttribute("ProgramID")]
public string programID { get; set; }
[XmlAttribute("MembershipID")]
public string membershipID { get; set; }
[XmlAttribute("TravelSector")]
public string travelSector { get; set; }
[XmlAttribute("LoyalLevel")]
public string loyalLevel { get; set; }
[XmlAttribute("SingleVendorInd")]
public string singleVendorInd { get; set; }
[XmlAttribute("SignupDate")]
public DateTime signupDate { get; set; }
[XmlAttribute("EffectiveDate")]
public DateTime effectiveDate { get; set; }
[XmlAttribute("ExpireDate")]
public DateTime expireDate { get; set; }
[XmlAttribute("RPH")]
public string rph { get; set; }
[XmlAttribute("VendorCode")]
public string vendorCode { get; set; }
}
[XmlRoot("BoardingPass")]
public class BoardingPass
{
[XmlElement("ForIndividualAirlineUse")]
public string forIndividualAirlineUse { get; set; }
[XmlElement("DigitalSignature")]
public DigitalSignature digitalSignature { get; set; }
}
[XmlRoot("DigitalSignature")]
public class DigitalSignature
{
[XmlAttribute("Type")]
public int _type { get; set; }
[XmlText]
public string value { get; set; }
}
[XmlRoot("Segment")]
public class Segment
{
[XmlElement("PNR")]
public PNR pnr { get; set; }
[XmlElement("NativeID")]
public string nativeID { get; set; }
[XmlElement("Flight")]
public Flight flight { get; set; }
[XmlElement("DepartureAirport")]
public Airport departureAirport { get; set; }
[XmlElement("ArrivalAirport")]
public Airport arrivalAirport { get; set; }
[XmlElement("Cabin")]
public string cabin { get; set; }
[XmlElement("SeatNumber")]
public string seatNumber { get; set; }
[XmlElement("CheckInSequenceNumber")]
public string checkInSequenceNumber { get; set; }
}
[XmlRoot("PNR")]
public class PNR
{
[XmlAttribute("URL")]
public string url { get; set; }
[XmlAttribute("Type")]
public string _type { get; set; }
[XmlAttribute("Instance")]
public string Instance { get; set; }
[XmlAttribute("ID")]
public string id { get; set; }
[XmlAttribute("ID_Context")]
public string id_Context { get; set; }
}
[XmlRoot("Flight")]
public class Flight
{
[XmlElement("NativeID")]
public string nativeID { get; set; }
[XmlElement("OperatingCarrier")]
public string operatingCarrier { get; set; }
[XmlElement("FlightNumber")]
public string flightNumber { get; set; }
[XmlElement("OperationalSuffix")]
public string operationalSuffix { get; set; }
[XmlElement("MarketingCarrier")]
public string marketingCarrier { get; set; }
[XmlElement("ScheduledDateOfDeparture")]
public DateTime scheduledDateOfDeparture { get; set; }
[XmlElement("ScheduledTimeOfDeparture")]
public DateTime scheduledTimeOfDeparture { get; set; }
[XmlElement("ScheduledDateOfArrival")]
public DateTime scheduledDateOfArrival { get; set; }
[XmlElement("ScheduledTimeOfArrival")]
public DateTime scheduledTimeOfArrival { get; set; }
}
public class Airport
{
[XmlElement("AirportCode")]
public string airportCode { get; set; }
[XmlElement("SourceIndicator")]
public int sourceIndicator { get; set; }
}
}
​
Okay. Weird. I created a whole new project on a different development machine and ran through the entire process with all clean XSD->CS and XSD->Sample XML and this code works fine. SO I guess I delete this question or someone can post an answer along the lines of "start over." The only step I know for certain that was different happened when I dragged the header tag from the XMLSchemaExplorer to the designer worksurface instead of the IATA_PASSENGERCONFORMANCEIDENTIFYRQ element. That generated a giant tree of branches, rather than the single node. This could have caused the issue BUT something else that might have happened: I suspect VS2010 on the older project kept references to earlier incarnations of the classes, or referenced wrong versions in backup folders. (This actually does happen with older VS versions.)

Deserialize XML with repeating elements

This is C# in VS2012 and building against .NET 4.5
I'm new to XML serialization/deserialization and trying to figure this out. I have XML
<?xml version="1.0"?>
<AvailabilityResponse>
<ApiKey>LZ6c#3O9#tq*BAyX4KGYBsCgZ*HpUDtrB*XI*WGLw</ApiKey>
<ResellerId>101</ResellerId>
<SupplierId>1004</SupplierId>
<ForeignReference>1234567890</ForeignReference>
<Timestamp>2015-08-06T05:20:49.000Z</Timestamp>
<RequestStatus>
<Status>SUCCESS</Status>
</RequestStatus>
<TTAsku>dcnt</TTAsku>
<TourAvailability>
<TourDate>2015-08-31</TourDate>
<TourOptions>
<DepartureTime>07:30 PM</DepartureTime>
</TourOptions>
<AvailabilityStatus>
<Status>AVAILABLE</Status>
</AvailabilityStatus>
</TourAvailability>
<TourAvailability>
<TourDate>2015-08-31</TourDate>
<TourOptions>
<DepartureTime>08:30 PM</DepartureTime>
</TourOptions>
<AvailabilityStatus>
<Status>AVAILABLE</Status>
</AvailabilityStatus>
</TourAvailability>
</AvailabilityResponse>
and I'm trying to deserialize into this class structure:
[Serializable]
public class AvailabilityResponse
{
public string ApiKey { get; set; }
public string ResellerId { get; set; }
public string SupplierId { get; set; }
public string ForeignReference { get; set; }
public DateTime Timestamp { get; set; }
public RequestStatus RequestStatus { get; set; }
public string TTAsku { get; set; }
public TourAvailability[] TourAvailability { get; set; }
}
[Serializable]
public class RequestStatus
{
public string Status { get; set; }
}
[Serializable]
public class TourAvailability
{
public DateTime TourDate { get; set; }
public TourOptions TourOptions { get; set; }
public AvailabilityStatus AvailabilityStatus { get; set; }
}
[Serializable]
public class AvailabilityStatus
{
public string Status { get; set; }
public string UnavailabilityReason { get; set; }
}
And I'm doing so with:
public static AvailabilityResponse DeserializeAvailabilityResponse(Stream replyStream)
{
XmlSerializer xmlSr = null;
XmlReader inreader = null;
if (replyStream != null)
{
XmlTextReader xmlreader = new XmlTextReader(replyStream);
XmlDocument respXml = new XmlDocument();
respXml.Load(xmlreader);
xmlreader.Close();
xmlSr = DeserializeXmlDoc(respXml, out inreader, typeof(AvailabilityResponse));
}
if (xmlSr != null && inreader != null)
{
AvailabilityResponse inventory = (AvailabilityResponse)xmlSr.Deserialize(inreader);
return inventory;
}
return null;
}
The problem is that when I examine the returned inventory item, the TourAvailability looks like this:
where I expected it to be like RequestStatus, for example, with the [+] allowing me to open it and see each element. Even if I misrepresented it I would expect there to be at least one TourAvailability, not zero.
I'm probably missing several things here but any help you can give is greatly appreciated. I have a bunch more of this kind of thing to deal with because our company is slightly changing direction.
Just use [XmlElement("TourAvailability")] attribute, Then you'll see the array's elemets.
public class AvailabilityResponse
{
public string ApiKey { get; set; }
public string ResellerId { get; set; }
public string SupplierId { get; set; }
public string ForeignReference { get; set; }
public DateTime Timestamp { get; set; }
public RequestStatus RequestStatus { get; set; }
public string TTAsku { get; set; }
[XmlElement("TourAvailability")]
public TourAvailability[] TourAvailability { get; set; }
}
BTW: You don't need those [Serializable] attributes
PS: Your deserialization code can be simplified as:
using (var f = File.OpenRead(filename))
{
XmlSerializer ser = new XmlSerializer(typeof(AvailabilityResponse));
var resp = (AvailabilityResponse)ser.Deserialize();
}
Try this
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
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)
{
Stream stream = File.Open(FILENAME, FileMode.Open);
AvailabilityResponse availabilityResponse = DeserializeAvailabilityResponse(stream);
}
public static AvailabilityResponse DeserializeAvailabilityResponse(Stream replyStream)
{
AvailabilityResponse availabilityResponse = null;
XmlReader inreader = null;
if (replyStream != null)
{
XmlSerializer xs = new XmlSerializer(typeof(AvailabilityResponse));
inreader = new XmlTextReader(replyStream);
availabilityResponse = (AvailabilityResponse)xs.Deserialize(inreader);
return availabilityResponse;
}
else
{
return null;
}
}
}
[XmlRoot("AvailabilityResponse")]
public class AvailabilityResponse
{
[XmlElement("ApiKey")]
public string ApiKey { get; set; }
[XmlElement("ResellerId")]
public int ResellerId { get; set; }
[XmlElement("SupplierId")]
public int SupplierId { get; set; }
[XmlElement("ForeignReference")]
public string ForeignReference { get; set; }
[XmlElement("Timestamp")]
public DateTime Timestamp { get; set; }
[XmlElement("RequestStatus")]
public RequestStatus RequestStatus { get; set; }
[XmlElement("TTAsku")]
public string TTAsku { get; set; }
[XmlElement("TourAvailability")]
public List<TourAvailability> TourAvailability { get; set; }
}
[XmlRoot("RequestStatus")]
public class RequestStatus
{
[XmlElement("Status")]
public string Status { get; set; }
}
[XmlRoot("TourAvailability")]
public class TourAvailability
{
[XmlElement("TourDate")]
public DateTime TourDate { get; set; }
[XmlElement("TourOptions")]
public TourOptions TourOptions { get; set; }
[XmlElement("AvailabilityStatus")]
public AvailabilityStatus AvailabilityStatus { get; set; }
}
[XmlRoot("TourOptions")]
public class TourOptions
{
public DateTime dTime { get; set; }
[XmlElement("DepartureTime")]
public string DepartureTime
{
get
{
return this.dTime.ToString("hh:mm tt");
}
set
{
this.dTime = DateTime.ParseExact(value, "hh:mm tt", CultureInfo.InvariantCulture);
}
}
}
[XmlRoot("AvailabilityStatus")]
public class AvailabilityStatus
{
[XmlElement("Status")]
public string Status { get; set; }
[XmlElement("UnavailabilityReason")]
public string UnavailabilityReason { get; set; }
}
}
​

Deserialize an XML file - an error in xml document (1,2)

I'm trying to deserialize an XML file which I receive from a vendor with XmlSerializer, however im getting this exception: There is an error in XML document (1, 2).InnerException Message "<delayedquotes xmlns=''> was not expected.. I've searched the stackoverflow forum, google and implemented the advice, however I'm still getting the same error. Please find the enclosed some content of the xml file:
<delayedquotes id="TestData">
<headings>
<title/>
<bid>bid</bid>
<offer>offer</offer>
<trade>trade</trade>
<close>close</close>
<b_time>b_time</b_time>
<o_time>o_time</o_time>
<time>time</time>
<hi.lo>hi.lo</hi.lo>
<perc>perc</perc>
<spot>spot</spot>
</headings>
<instrument id="Test1">
<title id="Test1">Test1</title>
<bid>0</bid>
<offer>0</offer>
<trade>0</trade>
<close>0</close>
<b_time>11:59:00</b_time>
<o_time>11:59:00</o_time>
<time>11:59:00</time>
<perc>0%</perc>
<spot>0</spot>
</instrument>
</delayedquotes>
and the code
[Serializable, XmlRoot("delayedquotes"), XmlType("delayedquotes")]
public class delayedquotes
{
[XmlElement("instrument")]
public string instrument { get; set; }
[XmlElement("title")]
public string title { get; set; }
[XmlElement("bid")]
public double bid { get; set; }
[XmlElement("spot")]
public double spot { get; set; }
[XmlElement("close")]
public double close { get; set; }
[XmlElement("b_time")]
public DateTime b_time { get; set; }
[XmlElement("o_time")]
public DateTime o_time { get; set; }
[XmlElement("time")]
public DateTime time { get; set; }
[XmlElement("hi")]
public string hi { get; set; }
[XmlElement("lo")]
public string lo { get; set; }
[XmlElement("offer")]
public double offer { get; set; }
[XmlElement("trade")]
public double trade { get; set; }
public delayedquotes()
{
}
}
Maybe you can try this code:
[Serializable, XmlRoot("delayedquotes"), XmlType("delayedquotes")]
public class DelayedQuotes
{
public DelayedQuotes()
{
instrument = new List<Instrument>();
}
[XmlElement("instrument")]
public List<Instrument> instrument { get; set; }
}
[XmlType("instrument")]
public class Instrument
{
[XmlElement("title")]
public string title { get; set; }
[XmlElement("bid")]
public double bid { get; set; }
[XmlElement("spot")]
public double spot { get; set; }
[XmlElement("close")]
public double close { get; set; }
[XmlElement("b_time")]
public DateTime b_time { get; set; }
[XmlElement("o_time")]
public DateTime o_time { get; set; }
[XmlElement("time")]
public DateTime time { get; set; }
[XmlElement("hi")]
public string hi { get; set; }
[XmlElement("lo")]
public string lo { get; set; }
[XmlElement("offer")]
public double offer { get; set; }
[XmlElement("trade")]
public double trade { get; set; }
}
Also, here is a sample code to test the classes above:
static void Main(string[] args)
{
Console.WriteLine("Initiating test!");
XmlSerializer serializer = new XmlSerializer(typeof(DelayedQuotes));
FileStream xmlFile = new FileStream("testXml.xml", FileMode.Open);
DelayedQuotes quotes = (DelayedQuotes) serializer.Deserialize(xmlFile);
Console.WriteLine("Finalizing test!");
}
Try this code.
var xml = System.IO.File.ReadAllText("test.xml");
using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(xml)))
{
XmlSerializer serializer = new XmlSerializer(typeof(delayedquotes));
delayedquotes data = (delayedquotes) serializer.Deserialize(stream);
}
I am not sure how you're deserializing the XML text into your object, but the following worked fine for me:
using System;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
namespace XMLSerializationTest
{
[Serializable, XmlRoot("delayedquotes"), XmlType("delayedquotes")]
public class delayedquotes
{
[XmlElement("instrument")]
public string instrument { get; set; }
[XmlElement("title")]
public string title { get; set; }
[XmlElement("bid")]
public double bid { get; set; }
[XmlElement("spot")]
public double spot { get; set; }
[XmlElement("close")]
public double close { get; set; }
[XmlElement("b_time")]
public DateTime b_time { get; set; }
[XmlElement("o_time")]
public DateTime o_time { get; set; }
[XmlElement("time")]
public DateTime time { get; set; }
[XmlElement("hi")]
public string hi { get; set; }
[XmlElement("lo")]
public string lo { get; set; }
[XmlElement("offer")]
public double offer { get; set; }
[XmlElement("trade")]
public double trade { get; set; }
public delayedquotes()
{
}
}
static class Program
{
static void Main(string[] args)
{
string source = #"<delayedquotes id=""TestData"">
<headings>
<title/>
<bid>bid</bid>
<offer>offer</offer>
<trade>trade</trade>
<close>close</close>
<b_time>b_time</b_time>
<o_time>o_time</o_time>
<time>time</time>
<hi.lo>hi.lo</hi.lo>
<perc>perc</perc>
<spot>spot</spot>
</headings>
<instrument id=""Test1"">
<title id=""Test1"">Test1</title>
<bid>0</bid>
<offer>0</offer>
<trade>0</trade>
<close>0</close>
<b_time>11:59:00</b_time>
<o_time>11:59:00</o_time>
<time>11:59:00</time>
<perc>0%</perc>
<spot>0</spot>
</instrument>
</delayedquotes>
";
var buff = Encoding.ASCII.GetBytes(source);
var ms = new MemoryStream(buff);
var xs = new XmlSerializer(typeof(delayedquotes));
var o = (delayedquotes)xs.Deserialize(ms);
Console.WriteLine("Title = {0}", o.instrument);
}
}
}

Categories

Resources