Unable to read XML to object - c#

I could use some help in reading this xml as an object in C#, the problem I have is with "ExtensionData" element, I can read everything in this xml except what's inside that element and I can't understand why, also I am receiving this xml the way it is, I can't alter it in any ways. I've tried pasting it as classes in visual studio, aswell as converting it using various websites but none of them were able to convert that node in an object.
<BufferEntitiesContainer>
<HeaderComandaBufferEntities>
<HeaderComandaBufferEntity>
<ProfilImportId>25</ProfilImportId>
<OrderNumber>999872748</OrderNumber>
<OrderDate>2021-03-12</OrderDate>
<BuyerILN>12345600</BuyerILN>
<BuyerName>CLIENT B2C</BuyerName>
<SalesDepartment>Vanzare WEB</SalesDepartment>
<Warehouse>A01</Warehouse>
<OrderCurrency>RON</OrderCurrency>
<DocumentFunctionCode>WB2C</DocumentFunctionCode>
<Remarks></Remarks>
<PaymentType></PaymentType>
<DeliveryPointILN>CIP-NX</DeliveryPointILN>
<OrderSerial>WB2C</OrderSerial>
<PaymentTerm></PaymentTerm>
<ExpectedDeliveryDate>2021-03-12</ExpectedDeliveryDate>
<ExtensionData><![CDATA[<ExtensionData>
<ExtensionFields>
<ExtensionTemplateID>3</ExtensionTemplateID>
<Fields>
<Root>
<Avans>0</Avans>
<PerioadaValabilitate dataInceput="1900-01-02" dataFinala="2078-12-31" />
<DS_CLIENT_ID>--</DS_CLIENT_ID>
<Nume_client>DAN NEDELCU</Nume_client>
<Adr_cod_post>011618</Adr_cod_post>
<Adr_judet>BUCURESTI</Adr_judet>
<Adr_loc>SECTOR 1</Adr_loc>
<Adr_str>NAUM</Adr_str>
<Adr_nr>1</Adr_nr>
<Adr_bl>1</Adr_bl>
<Adr_et>1</Adr_et>
<Adr_ap>1</Adr_ap>
<Adr_sect></Adr_sect>
<Nr_tel>0744835647</Nr_tel>
<Inf_gen>--</Inf_gen>
<Tip_pl>false</Tip_pl>
<Link_fact>--</Link_fact>
<Taxa_tr>0</Taxa_tr>
<Cupon_reducere>0</Cupon_reducere>
<CNP></CNP>
</Root>
</Fields>
</ExtensionFields>
</ExtensionData>]]></ExtensionData>
<OrderLines>
<DetaliuComanda>
<BuyerItemCode></BuyerItemCode>
<EAN>LEDLC-A6010E27/BC-WL</EAN>
<Remarks>Bec cu led A60 E27 10W 230V lumina rece Basic Well</Remarks>
<OrderedQuantity>1</OrderedQuantity>
<OrderedUnitNetPrice>8.8353</OrderedUnitNetPrice>
<UnitOfMeasure></UnitOfMeasure>
<Warehouse>A01</Warehouse>
</DetaliuComanda>
</OrderLines>
</HeaderComandaBufferEntity>
</HeaderComandaBufferEntities>
</BufferEntitiesContainer>

I managed to parse the string to an object this way:
XmlSerializer xmlSerializer = new XmlSerializer(typeof(BufferEntitiesContainer));
StreamReader streamReader = new StreamReader($#"{salesOrdersPath}{file}");
BufferEntitiesContainer so = (BufferEntitiesContainer)xmlSerializer.Deserialize(streamReader);
Console.WriteLine(so.HeaderComandaBufferEntities.HeaderComandaBufferEntity.ExtensionData);
XmlSerializer xmlInnerSerializer = new XmlSerializer(typeof(ExtensionData));
StringReader reader = new StringReader(so.HeaderComandaBufferEntities.HeaderComandaBufferEntity.ExtensionData);
ExtensionData soInner = (ExtensionData)xmlInnerSerializer.Deserialize(reader);
Console.WriteLine(soInner.ExtensionFields.Fields.Root.Nume_client);
So if anyone has this problem again, the solution was I made an object of type ExtensionData then I deserialized the inner xml string using StringReader to that object.
Thanks to all the people who gave me advices.

Related

Need Help Deserializing a Xml document in c#

I need help deserializing a XML file that i got on my machine. i have tried somthing like this.
private void button1_Click(object sender, EventArgs e)
{
DataSet ds = new DataSet();
XmlSerializer xmlSerializer = new XmlSerializer(typeof(DataSet));
FileStream readStream = new FileStream("D:\\Europoultry\\Connection Hjælp\\CIN_Example_2.xml", FileMode.Open);
ds = (DataSet)xmlSerializer.Deserialize(readStream);
readStream.Close();
dataGridView1.DataSource = ds.Tables[0];
}
but it says there is an error.
There is an error in XML-document (2, 2) System.InvalidOperationException: der is an error in XML-document(2,2): http://www.unece.org/cefact/namespaces/StandardBusinessDocumentHeader'> was not expected.
I can post the XML document if it is needed but it is a long document. Hope some of you can help.
Here is a part of the XML document
<?xml version="1.0" encoding="utf-8"?>
<sh:StandardBusinessDocument xmlns:sh="http://www.unece.org/cefact/namespaces/StandardBusinessDocumentHeader" xmlns:eanucc="urn:ean.ucc:2" xmlns:gdsn="urn:ean.ucc:gdsn:2" xmlns:align="urn:ean.ucc:align:2" xmlns:chemical_ingredient="urn:ean.ucc:align:chemical_ingredient:2" xmlns:food_beverage_tobacco="urn:ean.ucc:align:food_beverage_tobacco:2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.unece.org/cefact/namespaces/StandardBusinessDocumentHeader http://www.gdsregistry.org/2.8/schemas/sbdh/StandardBusinessDocumentHeader.xsd urn:ean.ucc:2 http://www.gdsregistry.org/2.8/schemas/CatalogueItemNotificationProxy.xsd urn:ean.ucc:2 http://www.gdsregistry.org/2.8/schemas/AttributeValuePairExtensionProxy.xsd urn:ean.ucc:2 http://www.gdsregistry.org/2.8/schemas/CaseLevelNonGTINLogisticsUnitExtensionProxy.xsd urn:ean.ucc:2 http://www.gdsregistry.org/2.8/schemas/TradeItemExtensionSpecificsProxy.xsd urn:ean.ucc:2 http://www.gdsregistry.org/2.8/schemas/ChemicalIngredientExtensionProxy.xsd urn:ean.ucc:2 http://www.gdsregistry.org/2.8/schemas/FoodAndBeverageTradeItemExtensionProxy.xsd">
<sh:StandardBusinessDocumentHeader>
<sh:HeaderVersion>1.0</sh:HeaderVersion>
<sh:Sender>
<sh:Identifier Authority="EAN.UCC">5790000011032</sh:Identifier>
</sh:Sender>
<sh:Receiver>
<sh:Identifier Authority="EAN.UCC">5790000500000</sh:Identifier>
</sh:Receiver>
<sh:DocumentIdentification>
<sh:Standard>EAN.UCC</sh:Standard>
<sh:TypeVersion>2.8</sh:TypeVersion>
<sh:InstanceIdentifier>DI-35346-34535-xt435345</sh:InstanceIdentifier>
<sh:Type>catalogueItemNotification</sh:Type>
<sh:CreationDateAndTime>2013-12-20T10:46:26+00:00</sh:CreationDateAndTime>
</sh:DocumentIdentification>
</sh:StandardBusinessDocumentHeader>
<eanucc:message>
<entityIdentification>
<uniqueCreatorIdentification>MSG-35346-34535-xt435345</uniqueCreatorIdentification>
<contentOwner>
<gln>5790000011032</gln>
</contentOwner>
</entityIdentification>
<eanucc:transaction>
<entityIdentification>
<uniqueCreatorIdentification>TRN-35346-34535-xt435345</uniqueCreatorIdentification>
<contentOwner>
<gln>5790000011032</gln>
</contentOwner>
</entityIdentification>
<command>
<eanucc:documentCommand>
<documentCommandHeader type="ADD">
<!--D8164-->
<entityIdentification>
<uniqueCreatorIdentification>CMD-35346-34535-xt435345</uniqueCreatorIdentification>
<contentOwner>
<gln>5790000011032</gln>
</contentOwner>
</entityIdentification>
</documentCommandHeader>
<documentCommandOperand>
<gdsn:catalogueItemNotification creationDateTime="2013-12-20T10:46:26+00:00" documentStatus="ORIGINAL" isReload="false">
<catalogueItem>
<catalogueItemState state="IN_PROGRESS"/>
<tradeItem>
<tradeItemUnitDescriptor>CASE</tradeItemUnitDescriptor>
<!--D8276-->
<tradeItemIdentification>
Try using xsd.exe for generating a c# class from this xml document.
There is an answer here: Generate C# class from XML
Then you can deserialize the xml document to the newly generated c# class
There are a few issues here that I can see. First, the XML you're trying to deserialize to a DataSet isn't a DataSet, so the deserialization would fail. Easiest way to do what you're trying to do is to make a set of POCOs that do represent your data, annotate them appropriately, and deserialize to those, and you can then use them as you would any other object. The exception you're getting, I believe is just that the XmlSerializer doesn't recognise your root element as being the one expected by the DataSet, or simply that it cannot correctly match the namespace. You can see more details about this here (https://msdn.microsoft.com/en-us/library/aa302290.aspx#trblshtxsd_topic5). Details of controlling XML Serialization/Deserialization via annotated POCOs can be found here (https://msdn.microsoft.com/en-us/library/2baksw0z(v=vs.110).aspx).

C# : Can I get XmlSerializer to deserialize an XML file without a namespace definition?

I am hoping someone can help me with this.
I need to serialize a request from XML so that it can be converted into a SOAP call. The problem is, I am having trouble succeeding when the xml is missing a xmlns definition.
First of all, I have a class called GetRegistrationStatusRequest. This was auto generated using the XSD tool from a customer provided XSD. The class looks as follows (Note that I have replaced the client sensitive URL)
//
// This source code was auto-generated by xsd, Version=4.0.30319.18020.
//
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.18020")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://some.url/srvc/getregistrationstatus/v1_0/request/")]
[System.Xml.Serialization.XmlRootAttribute(Namespace="http://some.url/srvc/getregistrationstatus/v1_0/request/", IsNullable=false)]
public partial class GetRegistrationStatusRequest : ServiceRequest {
... auto generated code
As mentioned, this is auto generated. I have included it for reference.
My Code for actually deserializing the Xml is as follows:
XmlSerializer serializer = new XmlSerializer(typeof(GetRegistrationStatusRequest));
GetRegistrationStatusRequest request = (GetRegistrationStatusRequest)serializer.Deserialize(new StringReader(RequestXml.OuterXml));
If I use XML as follows, it works fine:
<GetRegistrationStatusRequest xmlns="http://some.url//srvc/getregistrationstatus/v1_0/request/">
<PlateNo>PlateNo1</PlateNo>
</GetRegistrationStatusRequest>
However the XML that I am receiving (which is out of my control) does not have the xmlns defined. Instead it looks like this:
<GetRegistrationStatusRequest>
<PlateNo>PlateNo1</PlateNo>
</GetRegistrationStatusRequest>
When I attempt to deserialize this I get the message "The is an arror in XML document (1,2)"
I am wondering if it is actually possible to get the Xml to deserialize without needing the xmlns definition?
Any help would be greatly appreciated.
OK, I found the solution here, I hope it helps anyone else who has this issue:
http://calvinirwin.net/2011/02/10/xmlserialization-deserialize-causes-xmlns-was-not-expected/
My code now looks like this:
XmlRootAttribute xRoot = new XmlRootAttribute();
xRoot.ElementName = "GetRegistrationStatusRequest";
Root.IsNullable = true;
XmlSerializer serializer = new XmlSerializer(typeof(GetRegistrationStatusRequest), xRoot);
request = (GetRegistrationStatusRequest)serializer.Deserialize(new StringReader(RequestXml.OuterXml));
I had the same problem. Initially I tried using an XmlTextReader with the Namespaces property set to false. That code worked fine in a client application, but still encounters the error when used within the WCF service where the relevant type is defined.
The solution I found was to use an XmlDocument object and then correct the xmlns attribute before deserializing:
string ns = "http://some.url/srvc/getregistrationstatus/v1_0/request/";
XmlDocument doc = new XmlDocument();
doc.LoadXml(RequestXml.OuterXml);
doc.DocumentElement.SetAttribute("xmlns", ns);
XmlSerializer ser = new XmlSerializer(typeof(GetRegistrationStatusRequest), ns);
using (StringReader sr = new StringReader(doc.InnerXml)) {
GetRegistrationStatusRequest req = (GetRegistrationStatusRequest)ser.Deserialize(sr);
}
Note also the use of using to close and dispose of the StringReader.

Create JSON object from Multiline textbox windows phone

In my windows phone app, I'm in a need of creating a JSON object dynamically. i.e. I will know the property names only during run time. Also the property values can contain multiple lines.
Previously when I had to include multiple lines in a JSON object without any problem I used the following.
MemoryStream ms = new MemoryStream();
DataContractJsonSerializer ser = new DataContractJsonSerializer(obj.GetType());
ser.WriteObject(ms, obj);
using (StreamReader sr = new StreamReader(ms))
{
ms.Position = 0;
input = sr.ReadToEnd();
}
return input;
This worked very fine. But in order to use I should've known the class before hand. Unfortunately it is not possible.
Can anyone help me with any work around ?
Thank you.
DataContractJsonSerializer does not support such things.
You should try, for instance, Json.net.

Read XML values Webservice

I want to read xml on runtime, without save it on a path
After my searching i find that, In console application i need to use Console.Out for displaying result
xmlSerializer.Serialize(Console.Out, patient);
In Windows / Web Application we need to set path like
StreamWriter streamWriter = new StreamWriter(#"C:\test.xml");
but i need to read xml with out save it, i am using Webserive where i need to read it and take a decision that either it is valid or not
I hope i define it clearly..
Use the XmlDocument object.
There are several ways to load the XML, you can use the XmlDocument.Load() and specify your URL in there or use XmlDocument.LoadXml() to load the XML from a string.
You could use the XmlDocument.LoadXml class to read the received xml. There is no need to save it to disk.
try
{
XmlDocument doc = new XmlDocument();
doc.LoadXml(receivedXMLStr);
//valid xml
}
catch (XmlException xe)
{
//invalid xml
}
Use Linq2Xml..
XElement doc;
try
{
doc=XElement.Load(yourStream);
}
catch
{
//invalid XML
}
foreach(XElement node in doc.Descendants())
{
node.Value;//value of this node
nodes.Attributes();//all the attributes of this node
}
Thanks all of you for your reply, i want to laod my XML without save it on a local Path, because saving creating many XML.
Finally i find the solutions for load the XML from class on a Memory stream, I thinn this solution is very easy and optimize
XmlDocument doc = new XmlDocument();
System.Xml.Serialization.XmlSerializer serializer2 = new System.Xml.Serialization.XmlSerializer(Patients.GetType());
System.IO.MemoryStream stream = new System.IO.MemoryStream();
serializer2.Serialize(stream, Patients);
stream.Position = 0;
doc.Load(stream);
You need to use the Deserialize option to read the xml. Follow the below steps to achieve it,
Create a target class. It structure should represent the xml output.
After creating the class, use the below code to load your xml into the target object
TargetType result = null;
XmlSerializer worker = new XmlSerializer(typeof(TargetType));
result = worker.Deserialize("<xml>.....</xml>");
Now the xml is loaded into the object 'result' and use it.

An error occurred while parsing EntityName

I'm trying to load a xml document into an object XPathDocument in C#.
My xml documents include this line:
trés dégagée + rade
and when the parser arrives there it gives me this error:
"An error occurred while parsing EntityName"
I know that's normal cause of the character "é". Does anybody know how can I avoid this error... My idea is to insert into the xml document an entities declaration and after replace all special characters with entities...but it's long and I’m not sure if it's working. Do you have other ideas? Simpler?
Thanks a lot
Was about to post this and just then the servers went down. I think I've rewritten it correctly from memory:
I think that the problem lies within the fact that by default the XPathDocument uses an XmlTextReader to parse the contents of the supplied file and this XmlTextReader uses an EntityHandling setting of ExpandEntities.
In other words, when you rely on the default settings, an XmlTextReader will validate the input XML and try to resolve all entities. The better way is to do this manually by taking full control over the XmlReaderSettings (I always do it manually):
string myXMLFile = "SomeFile.xml";
string fileContent = LoadXML(myXMLFile);
private string LoadXML(string xml)
{
XPathDocument xDoc;
XmlReaderSettings xrs = new XmlReaderSettings();
// The following line does the "magic".
xrs.CheckCharacters = false;
using (XmlReader xr = XmlReader.Create(xml, xrs))
{
xDoc = new XPathDocument(xr);
}
if (xDoc != null)
{
XPathNavigator xNav = xDoc.CreateNavigator();
return xNav.OuterXml;
}
else
// Unable to load file
return null;
}
Typically this is caused by a mismatch between the encoding used to read the file and the files actually encoding.
At a guess I would say the file is UTF-8 encoded but you are reading it with a default encoding.
Try beefing up your question with more details to get a more definitive answer.

Categories