I have the following xml that i want to deserialize to a c# class:
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" xmlns:tns="http://www.s1.com/info/" xmlns:types="http://www.s1.com/info/" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Header>
<tns:SessionInfo>
<SessionId xsi:type="xsd:string">string</SessionId>
</tns:SessionInfo>
</soap:Header>
<soap:Body soap:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
<tns:LoginResponse>
<Result xsi:type="xsd:boolean">boolean</Result>
</tns:LoginResponse>
</soap:Body>
</soap:Envelope>
I am using the following classes in order to deserialize the xml:
public class SessionId
{
[XmlAttribute(AttributeName = "type", Namespace = "http://www.w3.org/2001/XMLSchema-instance")]
public string Type { get; set; }
[XmlText]
public string Text { get; set; }
}
[XmlRoot(ElementName = "SessionInfo", Namespace = "http://www.s1.com/info/")]
public class SessionInfo
{
[XmlElement(ElementName = "SessionId")]
public SessionId SessionId { get; set; }
[XmlAttribute(AttributeName = "id", Namespace = "")]
public string Id { get; set; }
[XmlText]
public string Text { get; set; }
}
[XmlRoot(ElementName = "Header", Namespace = "http://schemas.xmlsoap.org/soap/envelope/")]
public class Header
{
[XmlElement(ElementName = "SessionInfo", Namespace = "http://www.s1.com/info/")]
public SessionInfo SessionInfo { get; set; }
}
[XmlRoot(ElementName = "Result", Namespace = "")]
public class Result
{
[XmlAttribute(AttributeName = "type", Namespace = "http://www.w3.org/2001/XMLSchema-instance")]
public string Type { get; set; }
[XmlText]
public string Text { get; set; }
}
[XmlRoot(ElementName = "LoginResponse", Namespace = "http://www.s1.com/info/")]
public class LoginResponse
{
[XmlElement(ElementName = "Result")]
public Result Result { get; set; }
}
[XmlRoot(ElementName = "Body", Namespace = "http://schemas.xmlsoap.org/soap/envelope/")]
public class Body
{
[XmlElement(ElementName = "LoginResponse", Namespace = "http://www.s1.com/info/")]
public LoginResponse LoginResponse { get; set; }
[XmlAttribute(AttributeName = "encodingStyle", Namespace = "http://schemas.xmlsoap.org/soap/envelope/")]
public string EncodingStyle { get; set; }
[XmlText]
public string Text { get; set; }
}
[XmlRoot(ElementName = "Envelope", Namespace = "http://schemas.xmlsoap.org/soap/envelope/")]
public class Envelope
{
[XmlElement(ElementName = "Header", Namespace = "http://schemas.xmlsoap.org/soap/envelope/")]
public Header Header { get; set; }
[XmlElement(ElementName = "Body", Namespace = "http://schemas.xmlsoap.org/soap/envelope/")]
public Body Body { get; set; }
[XmlAttribute(AttributeName = "xsi", Namespace = "http://www.w3.org/2000/xmlns/")]
public string Xsi { get; set; }
[XmlAttribute(AttributeName = "xsd", Namespace = "http://www.w3.org/2000/xmlns/")]
public string Xsd { get; set; }
[XmlAttribute(AttributeName = "soapenc", Namespace = "http://www.w3.org/2000/xmlns/")]
public string Soapenc { get; set; }
[XmlAttribute(AttributeName = "tns", Namespace = "http://www.w3.org/2000/xmlns/")]
public string Tns { get; set; }
[XmlAttribute(AttributeName = "types", Namespace = "http://www.w3.org/2000/xmlns/")]
public string Types { get; set; }
[XmlAttribute(AttributeName = "soap", Namespace = "http://www.w3.org/2000/xmlns/")]
public string Soap { get; set; }
[XmlText]
public string Text { get; set; }
}
The problem is that the SessionId element is not getting deserialized, I am assuming due to the namespaces mismatch. I tried using an empty string as the namespace but that doesn't work either as it doesn't get recognized during deserialization.
Any insight on the problem is very much appreciated. Thank you!
First, SessionId has the wrong namespace. It inherits this from the parent, you need to explicitly specify that it doesn't have one by setting it to an empty string.
Secondly, the xsi:type has a special meaning, you shouldn't try to deserialise this. It's used to indicate the content type of an element - in this case, string - and will be used by the serialiser. The implication is that this is one of many acceptable types. The simplest way to define this is using object.
Putting those together, this should work:
[XmlElement(ElementName = "SessionId", Namespace = "")]
public object SessionId { get; set; }
SessionId should contain a string object with value string.
I'd also note various other minor things:
You shouldn't specify all the namespace bindings (e.g. Xsd) as part of the model. This is lower level than this model and will be handled by the serialiser.
You only need XmlRoot on the root
You don't need XmlText properties where there isn't any text
You need to make a similar change to above to deserialise Result
ElementName and AttributeName will default to the name of the property, so you don't have to specify these if that's what you want
Taking that into account, this model should work:
public class SessionInfo
{
[XmlElement(Namespace = "")]
public object SessionId { get; set; }
}
public class Header
{
[XmlElement(Namespace = "http://www.s1.com/info/")]
public SessionInfo SessionInfo { get; set; }
}
public class LoginResponse
{
[XmlElement(Namespace = "")]
public object Result { get; set; }
}
public class Body
{
[XmlElement(Namespace = "http://www.s1.com/info/")]
public LoginResponse LoginResponse { get; set; }
[XmlAttribute("encodingStyle", Namespace = "http://schemas.xmlsoap.org/soap/envelope/", Form = XmlSchemaForm.Qualified)]
public string EncodingStyle { get; set; }
}
[XmlRoot(Namespace = "http://schemas.xmlsoap.org/soap/envelope/")]
public class Envelope
{
[XmlElement]
public Header Header { get; set; }
[XmlElement]
public Body Body { get; set; }
}
You can see a working demo here. I've made one change to the source XML - I changed the Result value from boolean to true, else you'll get an exception because boolean isn't a valid value for that type.
Related
I am struggling actually with serializing my classes to the desired XML. I have problems placing the namespaces in the correct way.
here is the needed XML:
<?xml version="1.0" encoding="UTF-8"?> <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:q0="http://abc.def.schema" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<soapenv:Header>
<q0:LoginScopeHeader>
<organizationName>WebService Test Account</organizationName>
</q0:LoginScopeHeader>
<q0:SessionHeader>
<sessionId>00f63ba748474ebba5a5ce0f8fdf7ac4</sessionId>
</q0:SessionHeader>
</soapenv:Header>
<soapenv:Body>
<q0:GroupSet>
<staticGroup>
<number>10000</number>
<name>Gruppe A</name>
<conference>false</conference>
<activated>true</activated>
<personsCounter>0</personsCounter>
<messageName xsi:nil="true"/>
<personNumber xsi:nil="true"/>
</staticGroup>
<staticGroup>
<number>10000</number>
<name>Gruppe A</name>
<conference>false</conference>
<activated>true</activated>
<personsCounter>0</personsCounter>
<messageName xsi:nil="true"/>
<personNumber xsi:nil="true"/>
</staticGroup>
</q0:GroupSet>
</soapenv:Body>
Actually my class representation looks like this:
[XmlRoot(ElementName = "Envelope")]
public class Envelope
{
[XmlElement(ElementName = "Header")]
public Header Header { get; set; }
[XmlElement(ElementName = "Body")]
public Body Body { get; set; }
[XmlAttribute(AttributeName = "soapenv")]
public string Soapenv { get; set; }
[XmlAttribute(AttributeName = "q0")]
public string Q0 { get; set; }
[XmlAttribute(AttributeName = "xsd")]
public string Xsd { get; set; }
[XmlAttribute(AttributeName = "xsi")]
public string Xsi { get; set; }
}
[XmlRoot(ElementName = "LoginScopeHeader")]
public class LoginScopeHeader
{
[XmlElement(ElementName = "organizationName")]
public string OrganizationName { get; set; }
}
[XmlRoot(ElementName = "SessionHeader")]
public class SessionHeader
{
[XmlElement(ElementName = "sessionId")]
public string SessionId { get; set; }
}
[XmlRoot(ElementName = "Header")]
public class Header
{
[XmlElement(ElementName = "LoginScopeHeader")]
public LoginScopeHeader LoginScopeHeader { get; set; }
[XmlElement(ElementName = "SessionHeader")]
public SessionHeader SessionHeader { get; set; }
}
[XmlRoot(ElementName = "Body")]
public class Body
{
[XmlElement(ElementName = "GroupSet")]
public GroupSet GroupSet { get; set; }
}
[XmlRoot(ElementName = "GroupSet")]
public class GroupSet
{
[XmlElement(ElementName = "staticGroup")]
public List<StaticGroup> StaticGroup { get; set; }
}
[XmlRoot(ElementName = "staticGroup")]
public class StaticGroup
{
[XmlElement(ElementName = "number")]
public string Number { get; set; }
[XmlElement(ElementName = "name")]
public string Name { get; set; }
[XmlElement(ElementName = "conference")]
public string Conference { get; set; }
[XmlElement(ElementName = "activated")]
public string Activated { get; set; }
[XmlElement(ElementName = "personsCounter")]
public string PersonsCounter { get; set; }
[XmlElement(ElementName = "messageName")]
public MessageName MessageName { get; set; }
[XmlElement(ElementName = "personNumber")]
public PersonNumber PersonNumber { get; set; }
}
[XmlRoot(ElementName = "messageName")]
public class MessageName
{
[XmlAttribute(AttributeName = "nil")]
public string Nil { get; set; }
}
[XmlRoot(ElementName = "personNumber")]
public class PersonNumber
{
[XmlAttribute(AttributeName = "nil")]
public string Nil { get; set; }
}
And here the extension method for the serialization:
public static string XmlSerialize<T>(this T item, bool removeNamespaces = true)
{
object locker = new object();
XmlSerializerNamespaces xmlns = new XmlSerializerNamespaces();
xmlns.Add("xsi", "http://www.w3.org/2001/XMLSchema-instance");
xmlns.Add("xsd", "http://www.w3.org/2001/XMLSchema");
xmlns.Add("soapenv", "http://schemas.xmlsoap.org/soap/envelope/");
XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
settings.OmitXmlDeclaration = true;
lock (locker)
{
StringBuilder stringBuilder = new StringBuilder();
using (StringWriter stringWriter = new StringWriter(stringBuilder))
{
using (XmlWriter xmlWriter = XmlWriter.Create(stringWriter, settings))
{
if (removeNamespaces)
{
xmlSerializer.Serialize(xmlWriter, item, xmlns);
}
else { xmlSerializer.Serialize(xmlWriter, item); }
return stringBuilder.ToString();
}
}
}
}
I have actually no clue how the get the namespaces serialized like in the above XML.
What do I miss? Any help is highly appreciated
You need to assign your serialisation attributes with the appropriate namespaces. The Envelope, Body and Header elements have the namespace http://schemas.xmlsoap.org/soap/envelope/. So your Envelope class should look like this:
[XmlRoot(ElementName = "Envelope", Namespace = "http://schemas.xmlsoap.org/soap/envelope/")]
public class Envelope
{
[XmlElement(ElementName = "Header")]
public Header Header { get; set; }
[XmlElement(ElementName = "Body")]
public Body Body { get; set; }
}
You have added the namespace prefixes (q0, xsi, xsd) as properties of your Envelope class, this is not necessary so you can remove them.
The other namespace involved is http://abc.def.schema which has the q0 prefix. You should assign that where needed at the top level, for example, in the Body class, it should be assigned to the GroupSet property:
[XmlRoot(ElementName = "Body", Namespace = "http://schemas.xmlsoap.org/soap/envelope/")]
public class Body
{
[XmlElement(ElementName = "GroupSet", Namespace = "http://abc.def.schema")]
public GroupSet GroupSet { get; set; }
}
When you come to serialize, at the moment you are not telling the serializer about the q0 namespace prefix. So you need to add this in your XmlSerialize<T> extension method:
xmlns.Add("q0", "http://abc.def.schema");
Your StaticGroup element does not have a namespace defined in your example XML. So your GroupSet needs to define an empty namespace here:
[XmlRoot(ElementName = "GroupSet", Namespace = "http://abc.def.schema")]
public class GroupSet
{
[XmlElement(ElementName = "staticGroup", Namespace = "")]
public List<StaticGroup> StaticGroup { get; set; }
}
UPDATE_1:
I have added the namespaces as suggested by jdweng like so:
[XmlRoot(ElementName = "Envelope", Namespace = "http://schemas.xmlsoap.org/soap/envelope/")]
public class Envelope
{
[XmlElement(ElementName = "Header")]
public Header Header { get; set; }
[XmlElement(ElementName = "Body")]
public Body Body { get; set; }
[XmlAttribute(AttributeName = "soapenv")]
public string Soapenv { get; set; }
[XmlAttribute(AttributeName = "q0")]
public string Q0 { get; set; }
[XmlAttribute(AttributeName = "xsd")]
public string Xsd { get; set; }
[XmlAttribute(AttributeName = "xsi")]
public string Xsi { get; set; }
}
[XmlRoot(ElementName = "Header", Namespace = http://schemas.xmlsoap.org/soap/envelope/")]
public class Header
{
[XmlElement(ElementName = "LoginScopeHeader")]
public LoginScopeHeader LoginScopeHeader { get; set; }
[XmlElement(ElementName = "SessionHeader")]
public SessionHeader SessionHeader { get; set; }
}
[XmlRoot(ElementName = "Body", Namespace = "http://schemas.xmlsoap.org/soap/envelope/")]
public class Body
{
[XmlElement(ElementName = "PersonSet")]
public PersonSet PersonSet { get; set; }
}
but now I get the following XML:
<soapenv:Envelope xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
<soapenv:Header>
<soapenv:LoginScopeHeader>
<soapenv:organizationName>Blablabla</soapenv:organizationName>
</soapenv:LoginScopeHeader>
<soapenv:SessionHeader>
<soapenv:sessionId>654654654654654654654</soapenv:sessionId>
</soapenv:SessionHeader>
</soapenv:Header>
<soapenv:Body>
<soapenv:PersonSet>
<soapenv:elements>
<soapenv:active>true</soapenv:active>
<soapenv:number>321321321</soapenv:number>
<soapenv:name1>John</soapenv:name1>
<soapenv:name2>Doe</soapenv:name2>
<soapenv:language>DE</soapenv:language>
<soapenv:extra />
<soapenv:remarks>remarks</soapenv:remarks>
<soapenv:pin>65454</soapenv:pin>
<soapenv:onDutyManagement>false</soapenv:onDutyManagement>
<soapenv:onDutyManagementAutomaticLogoutDuration>0</soapenv:onDutyManagementAutomaticLogoutDuration>
<soapenv:onDutyManagementNotification>false</soapenv:onDutyManagementNotification>
<soapenv:contactDataManager>false</soapenv:contactDataManager>
<soapenv:contactDataManagedBy nil="1" />
<soapenv:caseManagerAccessMode>NO_ACCESS</soapenv:caseManagerAccessMode>
<soapenv:plannedPeriodsOfAbsence nil="1" />
<soapenv:groups>
<soapenv:elements>
<soapenv:active>true</soapenv:active>
<soapenv:conference_moderator>false</soapenv:conference_moderator>
<soapenv:time_offset>0</soapenv:time_offset>
<soapenv:groupNumber>123456</soapenv:groupNumber>
</soapenv:elements>
</soapenv:groups>
<soapenv:devices>
<soapenv:elements>
<soapenv:callingNumberOrEmail>s_c#gmx.ch</soapenv:callingNumberOrEmail>
<soapenv:prio_working_hours>1</soapenv:prio_working_hours>
<soapenv:prio_non_working_hours>0</soapenv:prio_non_working_hours>
<soapenv:dtmfExtensionNumber />
<soapenv:deviceName>EMail Privat</soapenv:deviceName>
</soapenv:elements>
</soapenv:devices>
</soapenv:elements>
</soapenv:PersonSet>
</soapenv:Body>
</soapenv:Envelope>
When I deserialize the XML below, from a third-party, my objects are always null.
XML
<?xml version="1.0"?>
<OrderImport xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<Reply i:nil="true">
</Reply>
<ReplyStatus i:nil="true">
<DebugInfo>
</DebugInfo>
<PerformanceLogInfo>
</PerformanceLogInfo>
</ReplyStatus>
<Reply>
<OrderNumber>4063286</OrderNumber>
</Reply>
<ReplyStatus>
<Result>0</Result>
<Message>
</Message>
</ReplyStatus>
</OrderImport>
C# Class
[XmlRoot(ElementName = "OrderImport")]
public class OrderImport
{
[XmlElement(ElementName = "Reply")]
public List<Reply> Reply { get; set; }
[XmlElement(ElementName = "ReplyStatus")]
public List<ReplyStatus> ReplyStatus { get; set; }
[XmlAttribute(AttributeName = "i", Namespace = "http://www.w3.org/2000/xmlns/")]
public string I { get; set; }
}
[XmlRoot(ElementName= "Reply")]
public class Reply
{
[XmlAttribute(AttributeName = "nil", Namespace = "http://www.w3.org/2001/XMLSchema-instance")]
public string Nil { get; set; }
[XmlElement(ElementName = "OrderNumber")]
public string OrderNumber { get; set; }
}
[XmlRoot(ElementName = "ReplyStatus")]
public class ReplyStatus
{
[XmlElement(ElementName = "DebugInfo")]
public string DebugInfo { get; set; }
[XmlElement(ElementName = "PerformanceLogInfo")]
public string PerformanceLogInfo { get; set; }
[XmlAttribute(AttributeName = "nil", Namespace = "http://www.w3.org/2001/XMLSchema-instance")]
public string Nil { get; set; }
[XmlElement(ElementName = "Result")]
public string Result { get; set; }
[XmlElement(ElementName = "Message")]
public string Message { get; set; }
}
I believe the problem has to do with the first occurrence of the objects Reply and ReplyStatus being null.
I'm trying to deserialize like so
httpResponseMessage.Content.ReadAsAsync<OrderImport>().Result;
However, I've found that if I deserialize like this it works just fine
stringres = httpResponseMessage.Content.ReadAsStringAsync().Result;
using (var stringreader = new StringReader(stringres))
{
var result = (OrderImport)xmlSerializer.Deserialize(stringreader);
}
I'm looking for a way with C# which I can deserialize XML below into a class. I can read it with XmlDocument.LoadXml() but I want to deserialize it into the object.
I tried to use XmlSerializer for the object:
[XmlRoot(ElementName = "properties", Namespace = "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata") ]
public class MyDto
{
[XmlElement(ElementName = "ObjectID", Namespace = "http://schemas.microsoft.com/ado/2007/08/dataservices")]
public string ObjectID { get; set; }
public string ContactID { get; set; }
}
My Code (memory stream is filled with xml):
var ms = new MemoryStream();
var w = XmlWriter.Create(ms, new XmlWriterSettings
{
Indent = true,
IndentChars = " ",
OmitXmlDeclaration = false,
Encoding = new UTF8Encoding(false),
});
XmlSerializer serializer = new XmlSerializer(typeof(MyDto));
var data = (MyDto)serializer.Deserialize(ms);
but I got the error
System.InvalidOperationException: There is an error in XML document (0, 0). ---> System.Xml.XmlException: Root element is missing.
<?xml version="1.0" encoding="utf-8"?>
<Content type="application/xml">
<m:properties xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata">
<d:ObjectID xmlns:d="http://schemas.microsoft.com/ado/2007/08/dataservices">920D2</d:ObjectID>
<d:ContactID xmlns:d="http://schemas.microsoft.com/ado/2007/08/dataservices">99999</d:ContactID>
</m:properties>
</Content>
Your class object for XmlSerializer quite wrong or not suitable for your XML.
You can get your proper class object for your xml from xmltocsharp
Try below class object.
[XmlRoot("ObjectID", Namespace = "http://schemas.microsoft.com/ado/2007/08/dataservices")]
public class ObjectID
{
[XmlAttribute("d", Namespace = "http://www.w3.org/2000/xmlns/")]
public string D { get; set; }
[XmlText]
public string Text { get; set; }
}
[XmlRoot("ContactID", Namespace = "http://schemas.microsoft.com/ado/2007/08/dataservices")]
public class ContactID
{
[XmlAttribute("d", Namespace = "http://www.w3.org/2000/xmlns/")]
public string D { get; set; }
[XmlText]
public string Text { get; set; }
}
[XmlRoot("properties", Namespace = "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata")]
public class Properties
{
[XmlElement("ObjectID", Namespace = "http://schemas.microsoft.com/ado/2007/08/dataservices")]
public ObjectID ObjectID { get; set; }
[XmlElement("ContactID", Namespace = "http://schemas.microsoft.com/ado/2007/08/dataservices")]
public ContactID ContactID { get; set; }
[XmlAttribute("m", Namespace = "http://www.w3.org/2000/xmlns/")]
public string M { get; set; }
}
[XmlRoot("Content")]
public class MyDto
{
[XmlElement("properties", Namespace = "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata")]
public Properties Properties { get; set; }
[XmlAttribute("type")]
public string Type { get; set; }
}
Output:
I am trying to extract the data contained the
in the a SOAP Response XML that I have that contains multiple and variable namespaces in an SSIS Script component using C#.
My XML looks like this:
<?xml version="1.0" encoding="UTF-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<ns3:getCacheEntryResponse xmlns:ns3="http://com.vedaadvantage/dp3/Enterprise/StandardTradeCreditCommercial/SilverChef/IndividualCommercialService" xmlns:ns2="http://com.vedaadvantage/dp3/Enterprise/StandardTradeCreditCommercial/SilverChef" xmlns:ns4="http://com.vedaadvantage/dp3/Enterprise/StandardTradeCreditCommercial/SilverChef/IndividualCommercialDecision" xmlns:ns5="http://vedaadvantage.com/dp3/service/fault" xmlns:ns6="http://com/vedaadvantage/dp3/businessDecisionResultOverride" xmlns:ns7="http://com.vedaadvantage/dp3/connectors" xmlns:ns8="http://com.vedaadvantage/dp3/connectors/vedaxml/vedascore" xmlns:ns9="http://com.vedaadvantage/dp3/connectors/vedaxml/individualalerts">
<ns3:CacheEntry>
<cacheEntryData><Response xmlns="http://com.vedaadvantage/dp3/connectors/vedaxml/vedascore" xmlns:b="http://com.vedaadvantage/dp3/connectors"><enquiryReport><primaryMatch><bureauReference>805917662</bureauReference><individual><individualName><familyName>MOHAMMADINEJAD</familyName><firstGivenName>ALI</firstGivenName><createDate>2014-07-15</createDate></individualName><gender>male</gender><dateOfBirth>1982-01-06</dateOfBirth><driversLicenceNumber><countryCodes>AU</countryCodes><value/></driversLicenceNumber><b:address><b:unitNumber/><b:streetNumber>43</b:streetNumber><b:property>43</b:property><b:streetName>KING EDWARD</b:streetName><b:streetType>AVE</b:streetType><b:suburb>ALBION</b:suburb><b:city/><b:state>VIC</b:state><b:postcode>3020</b:postcode><b:countryCode>AU</b:countryCode><b:addressType>residentialCurrent</b:addressType><b:createDate>2015-09-04</b:createDate></b:address></individual><individualConsumerCreditFile><creditEnquiry><accountType><accountType>UA</accountType><value>Utilities</value></accountType><role><consumerRoleTypeCodesResponse>principal</consumerRoleTypeCodesResponse></role><enquiryAmount><currencyCodeType/><value>0</value></enquiryAmount><coBorrower/><creditEnquirer>AGL ENGY SALES & MKTG LTD</creditEnquirer><clientReference/><consumerCreditEnquiryTypeResponse>creditApplication</consumerCreditEnquiryTypeResponse><enquiryDate>2015-09-04</enquiryDate></creditEnquiry><creditEnquiry><accountType><accountType>TC</accountType><value>Telecommunication Service</value></accountType><role><consumerRoleTypeCodesResponse>principal</consumerRoleTypeCodesResponse></role><enquiryAmount><currencyCodeType/><value>0</value></enquiryAmount><coBorrower/><creditEnquirer>VODAFONE DECISION POINT</creditEnquirer><clientReference>1-DCQJWZG</clientReference><consumerCreditEnquiryTypeResponse>creditApplication</consumerCreditEnquiryTypeResponse><enquiryDate>2014-07-15</enquiryDate></creditEnquiry></individualConsumerCreditFile><individualCommercialCreditFile><creditEnquiry><accountType><commercialAccountTypeCodesResponse>CR</commercialAccountTypeCodesResponse><value>Commercial Rental</value></accountType><enquiryAmount><currencyCodeType/><value>25000</value></enquiryAmount><role><commercialRoleTypeCodesResponse>principal</commercialRoleTypeCodesResponse></role><coBorrower/><creditEnquirer>GOGETTA EQUIPMENT FUNDING</creditEnquirer><clientReference/><commercialCreditEnquiryTypeResponse>creditEnquiry</commercialCreditEnquiryTypeResponse><enquiryDate>2016-04-04</enquiryDate></creditEnquiry></individualCommercialCreditFile><matchType>strong</matchType></primaryMatch><summaryData><summary><name>enquiry-amount</name><summaryType>amount</summaryType><currencyCode>AUD</currencyCode><value>25000</value></summary><summary><name>age-of-file</name><summaryType>months</summaryType><currencyCode/><value>20</value></summary><summary><name>age-of-subject</name><summaryType>years</summaryType><currencyCode/><value>34</value></summary><summary><name>time-at-address</name><summaryType>months</summaryType><currencyCode/><value>7</value></summary><summary><name>time-at-employer</name><summaryType>months</summaryType><currencyCode/><value/></summary><summary><name>defaults</name><summaryType>count</summaryType><currencyCode/><value>0</value></summary><summary><name>total-value-of-outstanding-defaults</name><summaryType>amount</summaryType><currencyCode>AUD</currencyCode><value>0</value></summary><summary><name>defaults-paid</name><summaryType>count</summaryType><currencyCode/><value>0</value></summary><summary><name>defaults-12</name><summaryType>count</summaryType><currencyCode/><value>0</value></summary><summary><name>defaults-12-paid</name><summaryType>count</summaryType><currencyCode/><value>0</value></summary><summary><name>defaults-12-unpaid</name><summaryType>count</summaryType><currencyCode/><value>0</value></summary><summary><name>defaults-24-paid</name><summaryType>count</summaryType><currencyCode/><value>0</value></summary><summary><name>defaults-24-unpaid</name><summaryType>count</summaryType><currencyCode/><value>0</value></summary><summary><name>defaults-36-paid</name><summaryType>count</summaryType><currencyCode/><value>0</value></summary><summary><name>defaults-36-unpaid</name><summaryType>count</summaryType><currencyCode/><value>0</value></summary><summary><name>time-since-last-default</name><summaryType>months</summaryType><currencyCode/><value/></summary><summary><name>total-credit-enquiries</name><summaryType>count</summaryType><currencyCode/><value>3</value></summary><summary><name>credit-enquiries-1</name><summaryType>count</summaryType><currencyCode/><value>1</value></summary><summary><name>credit-enquiries-3</name><summaryType>count</summaryType><currencyCode/><value>1</value></summary><summary><name>credit-enquiries-6</name><summaryType>count</summaryType><currencyCode/><value>1</value></summary><summary><name>credit-enquiries-12</name><summaryType>count</summaryType><currencyCode/><value>2</value></summary><summary><name>credit-enquiries-60</name><summaryType>count</summaryType><currencyCode/><value>3</value></summary><summary><name>time-since-last-enquiry</name><summaryType>months</summaryType><currencyCode/><value>7</value></summary><summary><name>telco-and-utility-defaults</name><summaryType>count</summaryType><currencyCode/><value>0</value></summary><summary><name>telco-and-utility-defaults-12</name><summaryType>count</summaryType><currencyCode/><value>0</value></summary><summary><name>telco-and-utility-enquiries</name><summaryType>count</summaryType><currencyCode/><value>2</value></summary><summary><name>telco-and-utility-enquiries-6</name><summaryType>count</summaryType><currencyCode/><value>0</value></summary><summary><name>telco-and-utility-enquiries-12</name><summaryType>count</summaryType><currencyCode/><value>1</value></summary><summary><name>authorised-agents-enquiries-12</name><summaryType>count</summaryType><currencyCode/><value>0</value></summary><summary><name>authorised-agents-enquiries-60</name><summaryType>count</summaryType><currencyCode/><value>0</value></summary><summary><name>directorships-current</name><summaryType>count</summaryType><currencyCode/><value>0</value></summary><summary><name>directorships-previous</name><summaryType>count</summaryType><currencyCode/><value>0</value></summary><summary><name>judgements</name><summaryType>count</summaryType><currencyCode/><value>0</value></summary><summary><name>proprietorships</name><summaryType>count</summaryType><currencyCode/><value>0</value></summary><summary><name>adverse-on-file</name><summaryType/><currencyCode/><value>No</value></summary><summary><name>file-notes</name><summaryType/><currencyCode/><value>No</value></summary><summary><name>known-identities</name><summaryType>count</summaryType><currencyCode/><value>1</value></summary><summary><name>bankruptcies</name><summaryType>count</summaryType><currencyCode/><value>0</value></summary><summary><name>writs-and-summons</name><summaryType>count</summaryType><currencyCode/><value>0</value></summary><summary><name>external-administration-director</name><summaryType>count</summaryType><currencyCode/><value>0</value></summary></summaryData><scoreData><score><scorecardModel>0303</scorecardModel><relativeRisk>2.3</relativeRisk><vedascore1_1Index>4.0863</vedascore1_1Index><applicantOdds>26.9</applicantOdds><contributingFactor><impact>Greatly Decreases Risk</impact><value>Lack of Consumer Adverse Information</value></contributingFactor><contributingFactor><impact>Moderately Decreases Risk</impact><value>Number of Consumer Credit Applications</value></contributingFactor><contributingFactor><impact>Marginally Decreases Risk</impact><value>Individual Shopping Pattern</value></contributingFactor><contributingFactor><impact>Marginally Decreases Risk</impact><value>Current and Historic Credit Type Sought</value></contributingFactor><population><populationOdds>11.9</populationOdds></population><vedaScore>675</vedaScore><percentile>30</percentile><scoreType>VS 1.1 COMMERCIAL + CONSUMER</scoreType></score></scoreData></enquiryReport></Response></cacheEntryData>
<connectorGroup>vedaxml</connectorGroup>
<connectorId>vedascore</connectorId>
<connectorVersion>2014-08-28</connectorVersion>
<request><Request xmlns:ns2="http://com.vedaadvantage/dp3/connectors" xmlns="http://com.vedaadvantage/dp3/connectors/vedaxml/vedascore"><product><name>vedascoreFinancialCommercialPlusConsumer1_1</name><summary>true</summary></product><individual><individualName><familyName>Mohammadinejad</familyName><firstGivenName>Ali</firstGivenName><otherGivenName></otherGivenName></individualName><gender>unknown</gender><dateOfBirth>1982-01-06Z</dateOfBirth><driversLicenceNumber><countryCodes>AU</countryCodes><value>06011982</value></driversLicenceNumber><ns2:address><ns2:addressType>residentialCurrent</ns2:addressType><ns2:unitNumber>3 U</ns2:unitNumber><ns2:streetNumber>43</ns2:streetNumber><ns2:property>43</ns2:property><ns2:streetName>KING EDWARD</ns2:streetName><ns2:streetType>AVE</ns2:streetType><ns2:suburb>ALBION</ns2:suburb><ns2:state>VIC</ns2:state><ns2:postcode>3020</ns2:postcode><ns2:countryCode>AU</ns2:countryCode></ns2:address><role>principal</role></individual><enquiry><accountType><accountType>CR</accountType></accountType><enquiryAmount><currencyCodeType>AUD</currencyCodeType><value>25000</value></enquiryAmount><enquiryType>creditEnquiry</enquiryType></enquiry><customerReference>GoGetta</customerReference></Request></request>
</ns3:CacheEntry>
</ns3:getCacheEntryResponse>
</soap:Body>
</soap:Envelope>
I have used http://xmltocsharp.azurewebsites.net/ to generate my C# classes which look like this:
[XmlRoot(ElementName = "CacheEntry", Namespace = "http://com.vedaadvantage/dp3/Enterprise/StandardTradeCreditCommercial/SilverChef/IndividualCommercialService")]
public class CacheEntry
{
[XmlElement(ElementName = "cacheEntryData")]
public string CacheEntryData { get; set; }
[XmlElement(ElementName = "connectorGroup")]
public string ConnectorGroup { get; set; }
[XmlElement(ElementName = "connectorId")]
public string ConnectorId { get; set; }
[XmlElement(ElementName = "connectorVersion")]
public string ConnectorVersion { get; set; }
[XmlElement(ElementName = "request")]
public string Request { get; set; }
}
[XmlRoot(ElementName = "getCacheEntryResponse", Namespace = "http://com.vedaadvantage/dp3/Enterprise/StandardTradeCreditCommercial/SilverChef/IndividualCommercialService")]
public class GetCacheEntryResponse
{
[XmlElement(ElementName = "CacheEntry", Namespace = "http://com.vedaadvantage/dp3/Enterprise/StandardTradeCreditCommercial/SilverChef/IndividualCommercialService")]
public CacheEntry CacheEntry { get; set; }
[XmlAttribute(AttributeName = "ns3", Namespace = "http://www.w3.org/2000/xmlns/")]
public string Ns3 { get; set; }
[XmlAttribute(AttributeName = "ns2", Namespace = "http://www.w3.org/2000/xmlns/")]
public string Ns2 { get; set; }
[XmlAttribute(AttributeName = "ns4", Namespace = "http://www.w3.org/2000/xmlns/")]
public string Ns4 { get; set; }
[XmlAttribute(AttributeName = "ns5", Namespace = "http://www.w3.org/2000/xmlns/")]
public string Ns5 { get; set; }
[XmlAttribute(AttributeName = "ns6", Namespace = "http://www.w3.org/2000/xmlns/")]
public string Ns6 { get; set; }
[XmlAttribute(AttributeName = "ns7", Namespace = "http://www.w3.org/2000/xmlns/")]
public string Ns7 { get; set; }
[XmlAttribute(AttributeName = "ns8", Namespace = "http://www.w3.org/2000/xmlns/")]
public string Ns8 { get; set; }
[XmlAttribute(AttributeName = "ns9", Namespace = "http://www.w3.org/2000/xmlns/")]
public string Ns9 { get; set; }
}
[XmlRoot(ElementName = "Body", Namespace = "http://schemas.xmlsoap.org/soap/envelope/")]
public class Body
{
[XmlElement(ElementName = "getCacheEntryResponse", Namespace = "http://com.vedaadvantage/dp3/Enterprise/StandardTradeCreditCommercial/SilverChef/IndividualCommercialService")]
public GetCacheEntryResponse GetCacheEntryResponse { get; set; }
}
[XmlRoot(ElementName = "Envelope", Namespace = "http://schemas.xmlsoap.org/soap/envelope/")]
public class Envelope
{
[XmlElement(ElementName = "Body", Namespace = "http://schemas.xmlsoap.org/soap/envelope/")]
public Body Body { get; set; }
[XmlAttribute(AttributeName = "soap", Namespace = "http://www.w3.org/2000/xmlns/")]
public string Soap { get; set; }
}
Here is how I am trying to extract the cacheEntryData field but it is not retrieving the node list (xnList) and it is not returning anything in my foreach statement.
public override void CreateNewOutputRows()
{
string soap_resp = Variables.getCacheEntryRspXML.ToString();
soap_resp = soap_resp.Replace("\"\"", "\"");
System.Windows.Forms.MessageBox.Show(soap_resp);
XmlDocument agv = new XmlDocument();
agv.LoadXml(soap_resp);
XmlNamespaceManager nsmgr = new XmlNamespaceManager(agv.NameTable);
nsmgr.AddNamespace("soap", "http://schemas.xmlsoap.org/soap/envelope/");
nsmgr.AddNamespace("ns3", "http://com.vedaadvantage/dp3/Enterprise/StandardTradeCreditCommercial/SilverChef/IndividualCommercialService");
XmlNodeList xnList = agv.SelectNodes("//ns3:CacheEntry", nsmgr);
foreach (XmlNode xn in xnList)
{
var cacheEntryData = xn["ns3:CacheEntry"].InnerText;
System.Windows.Forms.MessageBox.Show(Convert.ToString(cacheEntryData));
}
}
This is very unusual. The code looks like in was html encoded so I had to html decode.
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.IO;
using System.Net;
namespace ConsoleApplication73
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
string xml = File.ReadAllText(FILENAME);
CreateNewOutputRows(xml);
}
static public void CreateNewOutputRows(string xml)
{
XDocument doc = XDocument.Parse(xml);
XElement cacheEntryData = doc.Descendants().Where(x => x.Name.LocalName == "cacheEntryData").FirstOrDefault();
string cacheEntryDataXml = WebUtility.HtmlDecode(cacheEntryData.ToString());
XElement cacheEntryData2 = XElement.Parse(cacheEntryDataXml);
}
}
}
VS2008, .NET Framework 3.5
We're utilizing the WebEx Xml API. Here's a sample Xml response from their web service that I'm trying to deserialize into .NET classes.
<?xml version="1.0" encoding="UTF-8"?>
<serv:message xmlns:serv="http://www.webex.com/schemas/2002/06/service" xmlns:com="http://www.webex.com/schemas/2002/06/common"
xmlns:event="http://www.webex.com/schemas/2002/06/service/event"><serv:header><serv:response><serv:result>SUCCESS</serv:result><serv:gsbStatus>PRIMARY</s
erv:gsbStatus></serv:response></serv:header>
<serv:body>
<serv:bodyContent xsi:type="event:lstsummaryEventResponse" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<event:matchingRecords>
<serv:total>2</serv:total>
<serv:returned>2</serv:returned>
<serv:startFrom>1</serv:startFrom>
</event:matchingRecords>
<event:event>
<event:sessionKey>999999</event:sessionKey>
<event:sessionName>Test Event 1</event:sessionName>
<event:sessionType>129</event:sessionType>
<event:hostWebExID>SomeName</event:hostWebExID>
<event:startDate>03/28/2012 14:30:00</event:startDate>
<event:endDate>03/28/2012 14:45:00</event:endDate>
<event:timeZoneID>11</event:timeZoneID>
<event:duration>15</event:duration>
<event:description></event:description>
<event:status>NOT_INPROGRESS</event:status>
<event:panelists></event:panelists>
<event:listStatus>PUBLIC</event:listStatus>
</event:event>
</serv:bodyContent>
</serv:body>
</serv:message>
Here's the class that we're deserializing into:
using System;
using System.Xml;
using System.Xml.Serialization;
using System.Xml.Schema;
using System.Collections.Generic;
namespace Masonite.MTier.WebEx
{
[Serializable()]
[XmlRoot("message", Namespace = "http://www.webex.com/schemas/2002/06/service")]
public class lstsummaryEventResponsexx
{
[XmlNamespaceDeclarations]
public XmlSerializerNamespaces xmlns = new XmlSerializerNamespaces();
public lstsummaryEventResponsexx()
{
xmlns.Add("serv", "http://www.webex.com/schemas/2002/06/service");
xmlns.Add("com", "http://www.webex.com/schemas/2002/06/common");
xmlns.Add("event", "http://www.webex.com/schemas/2002/06/service/event");
}
[XmlElement(ElementName = "header")]
public Header header { get; set; }
[XmlElement(ElementName = "body")]
public Body body { get; set; }
[Serializable()]
[XmlRoot("header")]
public class Header
{
[XmlElement(ElementName = "response")]
public Response response { get; set; }
}
[Serializable()]
[XmlRoot("body")]
[XmlInclude(typeof(lstsummaryEventResponse))]
public class Body
{
[XmlElement(ElementName = "bodyContent", Form = XmlSchemaForm.Qualified)]
public BodyContent bodyContent { get; set; }
}
[Serializable()]
public class lstsummaryEventResponse
{
}
[Serializable()]
[XmlRoot("response")]
public class Response
{
[XmlElement(ElementName = "result")]
public string result { get; set; }
[XmlElement(ElementName = "reason")]
public string reason { get; set; }
[XmlElement(ElementName = "gsbStatus")]
public string gsbStatus { get; set; }
[XmlElement(ElementName = "exceptionID")]
public string exceptionID { get; set; }
}
[Serializable()]
[XmlRoot("bodyContent")]
public class BodyContent
{
[XmlElement(ElementName = "matchingRecords", Namespace = "http://www.webex.com/schemas/2002/06/service/event")]
public MatchingRecords matchingRecords { get; set; }
[XmlElement(ElementName = "event", Namespace = "http://www.webex.com/schemas/2002/06/service/event")]
public List<EventSummary> events { get; set; }
}
[Serializable()]
[XmlRoot("matchingRecords")]
public class MatchingRecords
{
[XmlElement(ElementName = "total", Namespace = "http://www.webex.com/schemas/2002/06/service")]
public int total { get; set; }
[XmlElement(ElementName = "returned", Namespace = "http://www.webex.com/schemas/2002/06/service")]
public int returned { get; set; }
[XmlElement(ElementName = "startFrom", Namespace = "http://www.webex.com/schemas/2002/06/service")]
public int startFrom { get; set; }
}
[Serializable()]
[XmlRoot("event")]
public class EventSummary
{
[XmlElement(ElementName = "sessionKey")]
public long sessionKey { get; set; }
[XmlElement(ElementName = "sessionName")]
public string sessionName { get; set; }
[XmlElement(ElementName = "sessionType")]
public int sessionType { get; set; }
[XmlElement(ElementName = "hostWebExID")]
public string hostWebExID { get; set; }
[XmlElement(ElementName = "startDate")]
public string startDate { get; set; }
[XmlElement(ElementName = "endDate")]
public string endDate { get; set; }
[XmlElement(ElementName = "timeZoneID")]
public int timeZoneID { get; set; }
[XmlElement(ElementName = "duration")]
public int duration { get; set; }
[XmlElement(ElementName = "description")]
public string description { get; set; }
[XmlElement(ElementName = "status")]
public string status { get; set; }
[XmlElement(ElementName = "panelists")]
public string panelists { get; set; }
[XmlElement(ElementName = "listStatus")]
public listingType listStatus { get; set; }
}
}
}
The error I'm receiving:
The specified type was not recognized: name='lstsummaryEventResponse', namespace='http://www.webex.com/schemas/2002/06/service/event', at <bodyContent xmlns='http://www.webex.com/schemas/2002/06/service'>
I'm not sure how to provide the type lstsummaryEventResponse for the Deserialize method. I added another serializable class to my class above using that name, but get the same error. Any thoughts?
BodyContent can have the type event:lstsummaryEventResponse - so you have to declare the corresponding class, and then decorate the declaration of BodyContent as follows:
[Serializable()]
[XmlRoot("bodyContent")]
[XmlInclude("lstsummaryEventResponse")]
public class BodyContent {
}
Having said that, creating C# class with a serialization corresponding to some arbitrary XML is pretty tricky, I am not sure it is right approach