Help with serialization

L

lallous

Hello

I have the following XML string:

<?xml version="1.0" encoding="UTF-8"?>
<bool name="value" val="false" display="OFF" href="/value/"
xmlns="http://MyObj.org/ns/schema/1.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://MyObj.org/ns/schema/1.0 /MyObj/xsd"/>

Then I assign it to a StringReader and deserialize it against the following
class:

[XmlRoot("bool")]
public class MyObjBool
{
[XmlAttribute("name")]
public string name;
[XmlAttribute("val")]
public bool val;
}

The code snippet is:

s1 = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><?xml-stylesheet
type='text/xsl' href='/MyObj/xsl'?><bool name=\"value\" val=\"false\"
display=\"OFF\" href=\"/value/\" xmlns=\"http://MyObj.org/ns/schema/1.0\"
xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"
xsi:schemaLocation=\"http://MyObj.org/ns/schema/1.0 /MyObj/xsd\"/>";

StringReader sr = new StringReader(s1);
XmlSerializer xs = new XmlSerializer(typeof(MyObjBool));

try
{
MyObjBool ob = (MyObjBool) xs.Deserialize(sr);
}
catch (Exception e)
{
msg(e.ToString());
}

Which is firing the following exception:

System.InvalidOperationException: There is an error in XML document (1,
92). ---> System.InvalidOperationException: <bool
xmlns='http://MyObj.org/ns/schema/1.0'> was not expected.
at
Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationReaderMyObjBool.Read3_bool()
--- End of inner exception stack trace ---
at System.Xml.Serialization.XmlSerializer.Deserialize(XmlReader
xmlReader, String encodingStyle, XmlDeserializationEvents events)
at System.Xml.Serialization.XmlSerializer.Deserialize(XmlReader
xmlReader, String encodingStyle)
at System.Xml.Serialization.XmlSerializer.Deserialize(TextReader
textReader)
at wrap1.Program.Main(String[] args) in C:\test1\Program.cs:line 151


Why?

Why is it when I remove the xmlns attribute the DeSerialize works?

Regards,
Elias
 
N

Nicholas Paldino [.NET/C# MVP]

lallous,

With the XmlRoot attribute, you need to set the namespace as well for
the element. Your attribute declaration should look like this:

[XmlRoot(ElementName = "bool", Namespace =
"http://MyObj.org/ns/schema/1.0")]
public class MyObjBool

Hope this helps.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Top