Issue with xml to object c# using Xml.Serialization - c#

I have an old xml response and I cannot map it to an object as I normally do.
Using paste special> xml
:When I deserialize it, it's throwing "The specified type was not recognized: name='Array'"
Using class from https://xmltocsharp.azurewebsites.net/
:I can map to object but there is nothing in return property
<?xml version="1.0" encoding="ISO-8859-1"?>
<SOAP-ENV:Envelope SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns:tns="http://uat.api.sample.uk">
<SOAP-ENV:Body>
<ns1:directReportResponse xmlns:ns1="urn:Direct">
<return xsi:type="SOAP-ENC:Array" SOAP-ENC:arrayType="tns:DirectResult[1]">
<item xsi:type="tns:DirectResult">
<TMSReference xsi:type="xsd:string">sampleTMS</TMSReference>
<Postcode xsi:type="xsd:string">samplePostcode</Postcode>
<ExpectedDelivery xsi:type="xsd:string">2020-08-25</ExpectedDelivery>
</item>
</return>
</ns1:directReportResponse>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
After follow andyrut, I can map it to custom type but still no value in an item obj

The generated class does not know that a "return" tag is an array of "item" elements. You simply need to make the following modifications to your C# class:
Delete the class definition for Return.
Mark the Return data member as a list/array of Item's. Change the Return data member in the DirectReportResponse to a list and decorate it like so:
[XmlArray(ElementName="return", Namespace="")]
[XmlArrayItem(ElementName="item", Namespace="")]
public List<Item> Return { get; set; }
There's a Type specified in the Item XML, so decorate your Item class by adding the following line above it:
[XmlType(Namespace="http://uat.api.sample.uk", TypeName="DirectResult")]
You may need to tweak your C# class for the other specified types in the XML file.

Related

Deserialize XML having Multiple xsi:type attributes

I am working on deserializing XML file where a same class has different namespaces. I am getting error while The specified type was not recognized. Here is a snippet from the XML I am trying to parse
<BookingHistory xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:ns3="dbpnr" xsi:type="ns3:SegmentHistory" Segment="ID13" eventDate="2014-04-03" eventTime="05:29:00" actionType="Change"/>
<BookingHistory xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:ns3="dbpnr" xsi:type="ns3:SsrHistory" eventDate="2014-04-03" eventTime="14:06:00" actionType="Add">
<BookingHistory xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:ns3="dbpnr" xsi:type="ns3:RemarkHistory" eventDate="2014-04-03" eventTime="15:02:00" actionType="Add">
Here is the sample XML
https://drive.google.com/file/d/1RDOAGa2TECSIauSHkdYTuSNuTWx5GVb8/view
Any suggestions would be highly appreciated.

Ignoring namespaces in XML deserialize

I want to deserialize XML into object. I have no controll what xml i'm reciving, and into what object I'm deserializing.
I tried this: Can I make XmlSerializer ignore the namespace on deserialization? and it worked... almost.
my xml
<request xmlns:a="http://schemas.datacontract.org/2004/07/My.Contracts" xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://tempuri.org/">
<a:ProfileInfo i:type="a:ProfileAndBSymbol">
<a:BSymbol>_47</a:BSymbol>
<a:ProfileSymbol>FAJNY</a:ProfileSymbol>
</a:ProfileInfo>
</request>
a:ProfileInfo works fine, but i:type thrown an exception. How to ignore i:?
exception is in Polish and it is like this:
InvalidOperationException: type is invalid. name= ProfileAndBSymbol,
namespace=http://schemas.datacontract.org/2004/07/My.Contracts

How do I get multiple namespaces in XML C#?

Following is the XML format:
<?xml version="1.0" encoding="UTF-8"?>
<package version="2.0" unique-identifier="isbn0000000000000" xmlns="http://www.idpf.org/2007/opf">
<metadata xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:opf="http://www.idpf.org/2007/opf">
<dc:title>Eltern Family</dc:title>
<dc:creator></dc:creator>
<dc:publisher></dc:publisher>
<dc:rights></dc:rights>
<dc:identifier id="isbn0000000000000">0000000000000</dc:identifier>
<dc:language>de</dc:language>
<dc:date opf:event="publication">2019-02-11</dc:date>
</metadata>
</package>
Here I got the default Namespace by XDocument.Root.GetDefaultNamespace();. But as you can see, there are multiple namespaces in the <metadata> XML node. The problem is that, they are variable i.e., each XML may have different values, so I cannot declare a variable with one fixed value.
How do I get the namespaces, so that I can add values to the descendant elements?
Please help.
Regards
Aman
If, as you say, you want to set the content of dc:rights, then you need to get hold of that element.
You can do this by name - the 'qualified name' is made of of the namespace and a local name. The namespace prefix dc is not actually important in and of itself, it's just used as a shorthand to refer to the namespace within the document.
Assuming you have parsed this XML to an XDocument called doc:
XNamespace dc = "http://purl.org/dc/elements/1.1/"
var rights = doc.Descendants(dc + "rights").Single();
rights.Value = "text";

Monogame XML serialization with Content pipeline

I've been trying to implement an XML system for items in my game.. but I just cant get it to work.
I am using Monogame and the content pipeline that comes with it.
I've made an Inventory Class and an Item Class.
Here are the snippets from the Inventory Class (which would have the serialization):
public class Inventory
{
[XmlElement("Item")]
public static List<Item> itemList;
public Inventory (Vector2 _position)
{
itemList = new List<Item>();
}
public void LoadContent()
{
XmlSerializer deserializer = new XmlSerializer(typeof(Item));
TextReader reader = new StreamReader("Content/Items/itemEntities.xml");
object obj = deserializer.Deserialize(reader);
Inventory XmlData = (Inventory)obj;
reader.Close();
}
}
And then I creaded an XML file:
<?xml version="1.0" encoding="utf-8"?>
<XnaContent xmlns:ns="Microsoft.Xna.Framework">
<Asset Type="Game.Item[]">
<Item>
<itemType>Weapon</itemType>
<itemRarity>Rare</itemRarity>
<itemID>0001</itemID>
<positionID>
<X>1</X>
<Y>1</Y>
</positionID>
<name>The sword</name>
<description>Description</description>
</Item>
<Item>
<itemType>Equipment</itemType>
<itemRarity>Uncommon</itemRarity>
<itemID>0002</itemID>
<positionID>
<X>1</X>
<Y>1</Y>
</positionID>
<name>The Item</name>
<description>Description</description>
</Item>
<Item>
<itemType>Drone</itemType>
<itemRarity>Common</itemRarity>
<itemID>0003</itemID>
<positionID>
<X>1</X>
<Y>1</Y>
</positionID>
<name>The Drone</name>
<description>Description</description>
</Item>
</Asset>
</XnaContent>
The problem now is that I get the following error:
error: Importer 'XmlImporter' had unexpected failure!
Microsoft.Xna.Framework.Content.Pipeline.InvalidContentException: Could not resolve type 'Game.Item[]'.
I have read on some other questions here that I would have to make a reference, but I just can't find a way to make that. In the solution explorer I can see references, but when I click add, I dont see anything in Projects, only standard stuff like Frameworks etc. are there.
Oh and I have a constuctor with no arguments in Item class, so that should be fine.
One more thing. I have tried to write the list of items into an XML file and it worked perfectly..
Thanks in advance!
You need to add a reference to a compiled dll lib, which means, your types need to be defined in an external project.
Create another project that compiles into dll, define all your structs and classes there (at least those that need serialization), and add reference to the dll from the content manager by doing the following:
open content pipeline manager.
select root node ("Content").
On the properties tab click on "References".
Click on 'Add' and select the path to the dll file you generated from the other project.
I recently asked a similar question on the monogame community and currently its impossible to serialize types from your own project into / from xml without using another project that builds into a dll.

How to do simple XML schema validation with no namespaces in C#

I have generated a set of classes using xsd.exe and created an XML document from the resulting generated code. I would now like to validate the serialized class instance against the original xsd.
My XML is like this:
<?xml version="1.0" encoding="UTF-8"?>
<MyRoot xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
-- rest of XML document here
</MyRoot>
My XSD is like this:
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="MyRoot" type="MyRootType"/>
-- MyRootType definition and rest of XSD
</xs:schema>
When I try to validate the XML using a XmlReader, I get the following error:
"The 'MyRoot' element is not declared."
What could be wrong?
In your MyRoot element, you need to add the location of the XSD. I would also recommend defining the namespace (unless you have good reason not to).
<api:MyRoot xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'
xmlns:api='http://www.myserver.com/schema'
xsi:schemaLocation='http://www.myserver.com/schema http://www.myserver.com/schema/websuiterecord.xsd'>
</api:MyRoot>
This way, the validation tool knows where to find your XSD to validate your XML against.
The approach was correct, but the XSD was not infact being read. I corrected this and it worked as expected.

Categories

Resources