Home > Software engineering >  Deserialize XML with xmls:xsd and xmlns:xsi
Deserialize XML with xmls:xsd and xmlns:xsi

Time:10-28

I need to deserialize XML file to an object in C#:

<?xml version="1.0" encoding="utf-16"?>
<Test xmlns:xsd=http://www.w3.org/2001/XMLSchema xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance>
<Number>110658419900</Number>
<WorkorderName>2103477915XVN35S_FR_LEFTX111</WorkorderName>
<RequestDate>2022-10-13T16:53:13.2171314 02:00</RequestDate> 
<ShelfNumber>4</ShelfNumber> 
</Test>


public class Test
{
    public string Number { get; set; }
    public string WorkorderName { get; set; }
    public string RequestDate { get; set; }
    public string ShelfNumber { get; set; }
}

I am using this approach:

        try
        {
            XmlSerializer serializer = new XmlSerializer(typeof(Test));
            StreamReader reader = new StreamReader(fileSystemEventArgs.FullPath);
            Test test = (Test)serializer.Deserialize(reader);
            reader.Close();
            return test;
        }
        catch (Exception ex)
        {
            string message = ex.Message;
        }

But I am receiving an error:

{"There is an error in XML document (2, 17)."}

Everything is working If I remove this from XML: xmlns:xsd=http://www.w3.org/2001/XMLSchema xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance

I don't know why this is happening. How to solve this issue? How to ignore this xmls:xsd and xmls:xsi?

CodePudding user response:

That "xml" isn't valid xml, and the parser is correct to shout here. The xml should start (note the quotes):

<Test xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

(etc)

However, those are just namespace alias declarations, and those aliases are never used, so: you can also just delete them here, leaving your xml as starting

<Test>
  • Related