472,145 Members | 1,417 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,145 software developers and data experts.

xmlns=''> was not expected.

Hi guys,Does any1 know what this error is all about, what I am trying to do is deserialize a XML, below is my code, let me know what I am doing wrongpublic class test{xin = "<?xml version='1.0' encoding='UTF-8'?><InSession><PassWord>foo</PassWord><UserName>fo*@foo.com</UserName></InSession>";XmlSerializer serializer = new XmlSerializer(typeof(cXmlBS));XmlTextReader tr = new XmlTextReader(new System.IO.StringReader(xin));cXmlBS cx = (cXmlBS)serializer.Deserialize(tr);tr.Close();}pub lic class cXmlBS{public String PassWord;public String UserName;}System.InvalidOperationException: There is an error in XML document (1, 40). ---> System.InvalidOperationException: <InSession xmlns=''> was not expected.
at Microsoft.Xml.Serialization.GeneratedAssembly.XmlS erializationReader1.Read4_cXmlBS()
--- End of inner exception stack trace ---
at System.Xml.Serialization.XmlSerializer.Deserialize (XmlReader xmlReader, String encodingStyle)
at System.Xml.Serialization.XmlSerializer.Deserialize (XmlReader xmlReader)
at BathamWS.LoginService.BeginSession(String xin) in c:\inetpub\wwwroot\bathamws\loginws.asmx.cs:line 62
help is appreciated, thanksshailendra batham
Nov 12 '05 #1
4 58557
"Shailendra Batham" <sg******@sbcglobal.net> wrote in message news:Fj*****************@newssvr21.news.prodigy.co m...
Does any1 know what this error is all about, what I am trying to do is deserialize
a XML, below is my code, let me know what I am doing wrong : : System.InvalidOperationException: There is an error in XML document (1, 40).
---> System.InvalidOperationException: <InSession xmlns=''> was not expected.
at Microsoft.Xml.Serialization.GeneratedAssembly.XmlS erializationReader1.Read4_cXmlBS()


The XML you are trying to deserialize looks like this,

<InSession>
<PassWord>foo</PassWord>
<UserName>fo*@foo.com</UserName>
</InSession>

However, the class you are deserializing into looks like this,

public class cXmlBS
{
public String PassWord;
public String UserName;
}

The difference is the root element name. Your XML contains an element named
"InSession" (without xmlns, that's all the message is saying there, it's extraneous
to the problem at hand). However, Deserialize( ) only knows how to look for
an element named "cXmlBS". It did not expect to see an element named "In-
Session," that is all the InvalidOperationException is telling you.

There are two solutions, change the element name in the XML you're deserializing
to match the class/type name:

<cXmlBS>
<PassWord>foo</PassWord>
<UserName>fo*@foo.com</UserName>
</cXmlBS>

or you can decorate the class/type name with an XmlRootAttribute that tells the
XmlSerializer that you want the XML element "InSession" to correspond to the
class cXmlBS's root element.

[XmlRoot( "InSession")]
public class cXmlBS
{
public String PassWord;
public String UserName;
}
Derek Harmon
Nov 12 '05 #2
Thanks Derek for the help I got my problem solved,

I have another question.

<?xml version='1.0' encoding='UTF-8'?>
<State>
<California>
<City>
<LosAngeles></LosAngeles>
<SantaMonica></SantaMonica>
<City>
</California>
<Illinois>
<City>
<Chicago></Chicago>
<City>
</Illinois>
</State>

suppose this is my xml document, how can I achieve serialization and
deserialization on this xml and get the results.

"Derek Harmon" <lo*******@msn.com> wrote in message
news:%2****************@TK2MSFTNGP12.phx.gbl...
"Shailendra Batham" <sg******@sbcglobal.net> wrote in message
news:Fj*****************@newssvr21.news.prodigy.co m...
Does any1 know what this error is all about, what I am trying to do is
deserialize
a XML, below is my code, let me know what I am doing wrong

: :
System.InvalidOperationException: There is an error in XML document (1,
40).
---> System.InvalidOperationException: <InSession xmlns=''> was not
expected.
at
Microsoft.Xml.Serialization.GeneratedAssembly.XmlS erializationReader1.Read4_cXmlBS()


The XML you are trying to deserialize looks like this,

<InSession>
<PassWord>foo</PassWord>
<UserName>fo*@foo.com</UserName>
</InSession>

However, the class you are deserializing into looks like this,

public class cXmlBS
{
public String PassWord;
public String UserName;
}

The difference is the root element name. Your XML contains an element
named
"InSession" (without xmlns, that's all the message is saying there, it's
extraneous
to the problem at hand). However, Deserialize( ) only knows how to look
for
an element named "cXmlBS". It did not expect to see an element named "In-
Session," that is all the InvalidOperationException is telling you.

There are two solutions, change the element name in the XML you're
deserializing
to match the class/type name:

<cXmlBS>
<PassWord>foo</PassWord>
<UserName>fo*@foo.com</UserName>
</cXmlBS>

or you can decorate the class/type name with an XmlRootAttribute that
tells the
XmlSerializer that you want the XML element "InSession" to correspond to
the
class cXmlBS's root element.

[XmlRoot( "InSession")]
public class cXmlBS
{
public String PassWord;
public String UserName;
}
Derek Harmon

Nov 12 '05 #3
Apply XmlRoot attribute to your class:

[XmlRoot("InSession")]public class cXmlBS{public String PassWord;public String UserName;}
Nov 12 '05 #4
"Shailendra Batham" <sg******@sbcglobal.net> wrote in message news:uV****************@newssvr29.news.prodigy.com ...
<?xml version='1.0' encoding='UTF-8'?>
<State>
<California>
<City>
<LosAngeles></LosAngeles>
<SantaMonica></SantaMonica>
<City>
</California>
<Illinois>
<City>
<Chicago></Chicago>
<City>
</Illinois>
</State>

suppose this is my xml document, how can I achieve serialization and
deserialization on this xml and get the results.


It's not possible to serialize/deserialize this based on serialization
attributes alone because you've encoded the "data" into the element
names, instead of using the elements to describe it's "structure." (I'm
not going to preach why this is generally a bad idea.)

Instead, it's necessary to implement the IXmlSerializable interface.
Here's what you'll need for this little project:

* One XML schema document (which in this case, cannot
be too well structured, but you need on nevertheless),

* Two methods, one deserializing from an XmlReader and the
other serializing into an XmlWriter.

Making this more concrete involves crafting up the essential object
model you've presupposed in your desired XML document, so let
me do that first. These classes will be light on luxury (the IEnumerable
implementation isn't necessary for serialization, but to simplify the
test driver) while stressing relevance.

- - - States.cs
using System;
using System.Collections;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;

public class CityObj
{
string cityName;

public CityObj( string cityName)
{
this.cityName = cityName;
}

public string City
{
get
{
return this.cityName;
}
set
{
this.cityName = value;
}
}
}

public class StateObj : IEnumerable
{
string stateName;
ArrayList cityList;

public StateObj( string stateName)
{
this.stateName = stateName;
this.cityList = new ArrayList( );
}

public StateObj( string stateName, CityObj[ ] cities)
{
this.stateName = stateName;
this.cityList = new ArrayList( cities);
}

public CityObj Add( string cityName)
{
CityObj city = new CityObj( cityName);
this.cityList.Add( city);
return city;
}

public string StateName
{
get
{
return this.stateName;
}
set
{
this.stateName = value;
}
}

IEnumerator IEnumerable.GetEnumerator( )
{
return ((IEnumerable)( this.cityList)).GetEnumerator( );
}
}
public class StateCollection : IXmlSerializable, IEnumerable
{
ArrayList stateList;
bool deserializedOK;

public StateCollection( )
{
this.stateList = new ArrayList( );
this.deserializedOK = true;
}

public bool IsOK
{
get
{
return this.deserializedOK;
}
}

public int Count
{
get
{
return this.stateList.Count;
}
}

public StateObj Add( string stateName)
{
StateObj st = new StateObj( stateName);
this.stateList.Add( st);
return st;
}

public StateObj Add( StateObj state)
{
this.stateList.Add( state);
return state;
}

IEnumerator IEnumerable.GetEnumerator( )
{
return ((IEnumerable)( this.stateList)).GetEnumerator( );
}

public XmlSchema GetSchema( )
{
// TO BE SUPPLIED.
}

public void ReadXml( XmlReader reader)
{
// TO BE SUPPLIED.
}

public void WriteXml( XmlWriter writer)
{
// TO BE SUPPLIED.
}
}
- - -

The first method of IXmlSerializable that you're going to implement
is GetSchema( ). This method needs to return an XML Schema
Document describing the expected format of the serialized instance
XML. Since I can't anticipate all of the states / provinces that your
application might require, there's very little I can do as far as defining
<xs:element>'s of it's structure. Instead, the heart of the lax schema
I'm going to use is the <xs:any> (note that the processContent attribute
is not allowed, however the any element will permit you free-wheeling
lattitude in the content of that element).

Here's the schema document, complete for your perusal.

- - - state.xsd
<?xml version='1.0'?>
<xs:schema id="States" xmlns:xs='http://www.w3.org/2001/XMLSchema'>

<!-- Global Type Definitions -->
<xs:complexType name="StatesType">
<xs:sequence>
<!-- Allow literally any content in the empty xmlns='' -->
<xs:any namespace="##local" minOccurs="1" maxOccurs="unbounded" />
</xs:sequence>
</xs:complexType>

<!-- Global Element Declaration -->
<xs:element name="States" type="StatesType" />

</xs:schema>
- - -

Now let's fill out the GetSchema( ) method, which simply loads
this file and returns a SOM XmlSchema instance.

public XmlSchema GetSchema()
{
FileStream xsdFile = new FileStream( "State.xsd", FileMode.Open);

// Optional ValidationEventHandler can be passed as 2nd argument here.
XmlSchema xsd = XmlSchema.Read( xsdFile, null);

xsdFile.Close( );
return xsd;
}

Pretty self-explanatory. Normally if we had had a more stringent
schema document, the step in which XmlSerializer gets the schema
would also perform schema-validation and it could detect validation
errors here (or notify your program through a ValidationEventHandler
you register in the XmlSchema.Read( ) method above).

The example I'm demonstrating will put the serialized content into a
container element named after the class, StateCollection, but
within there the content closely corresponds to what you want.
You may re-align the object model as is necessary for the app
at hand, but make sure you retain the xsd and xsi namespace
declarations.

Writing the XML out is the simplest operation, taking advantage
of the IEnumerable support in the object model we're using. It's
a straightforward application of the XmlWriter class that the
XmlSerializer will pass to this method when time comes to serialize
the StateCollection instance (or other IXmlSerializable implementation).

public void WriteXml( XmlWriter writer)
{
writer.WriteStartElement( "State");
writer.WriteAttributeString( "xmlns", "xsd", null, "http://www.w3.org/2001/XMLSchema");
writer.WriteAttributeString( "xmlns", "xsi", null, "http://www.w3.org/2001/XMLSchema-instance");

foreach( StateObj st in this )
{
writer.WriteStartElement( st.StateName);

// Assuming <City> is required, even when there are no child elements;
// if <City> is optional based on the existence of child elements, then
// move WriteStartElement( "City") and WriteEndElement() inside foreach
// loop and use a firstTimeOnly flag to write them.
//
writer.WriteStartElement( "City");
foreach( CityObj city in st)
{
writer.WriteStartElement( city.City);
writer.WriteFullEndElement( );
}
writer.WriteFullEndElement( ); // </City>

writer.WriteFullEndElement(); // </StateName>
}

writer.WriteEndElement(); // </State>
}

The reading portion is probably the most complicated as it involves
we maintain a state machine. In this example, when I'm between
the <State> element and the <City> element, I know any elements
I encounter are state names. If I've already encountered a <City>
element, but not yet a </City> closing tag, then I know any elements
are city names contained by the last (in-scope) state name.

The key indications that I'm changing state in my reading routine
are based off of the reader's IsStartElement( ) method, and tests
of whether I've encountered a NodeType of XmlEndElement. At
these points I look at the node's LocalName (which is either "State",
a state name, "City", or a city name). Although the end element
won't yield a local name, by diligently pushing every name onto a
Stack when they were start elements, I can safely pop them off
when I need the name of the current end element.

In order to track the transitions of this state machine I use a 'depth'
indicator where the opening/closing <State> is at the most shallow
depth (betweenStateAndCity == 1) and city names after a <City>
are the greatest depth (betweenStateAndCity == 3).

public void ReadXml( XmlReader reader)
{
Stack hopper = new Stack( );
bool reachedEnd = false;
int betweenStateAndCity = 1;

try
{
StateObj currentState = null;
while ( reader.Read( ) && !reachedEnd )
{
if ( reader.IsStartElement( ) )
{
string name = reader.LocalName;
hopper.Push( name);

if ( 0 == name.CompareTo( "State"))
{
++betweenStateAndCity;
}
else if ( 0 == name.CompareTo( "City"))
{
++betweenStateAndCity;
}
else if ( ( 2 == betweenStateAndCity ) && ( null == currentState ) )
{
currentState = new StateObj( name);
}
else if ( ( 3 == betweenStateAndCity ) && ( null != currentState ) )
{
currentState.Add( name);
}
Debug.WriteLine( "pushed {0}", name);
}
else if ( reader.NodeType == XmlNodeType.EndElement )
{
if ( hopper.Count > 0 )
{
string name = hopper.Pop( ) as string;
if ( 0 == name.CompareTo( "City"))
{
this.Add( currentState);
currentState = null;
--betweenStateAndCity;
}
if ( 0 == name.CompareTo( "State"))
{
reachedEnd = true;
--betweenStateAndCity;
}
Debug.WriteLine( "popped {0}", (name == null)? "(null)": name);
}
}
}
}
catch ( XmlException xe)
{
Debug.WriteLine( xe.Message);
this.deserializedOK = false;
}
}

While the subtleties of the above code's state transitions settle,
let's create a test driver that tries out this solution. I mean, will
IXmlSerializable really work, after all this typing you've done,
and having decomposed the schema of your desired XML into
an XmlReader implementation? Maybe this was wasted effort,
you might be thinking, at least until you can execute a tangible
example.

Here is that example.

- - - StateApp.cs
public class App
{
public static void Main( )
{
// Create a StateCollection
//
StateCollection usa = new StateCollection( );

// Add the sunshine state..
//
StateObj ca = usa.Add( "California");
ca.Add( "LosAngeles");
ca.Add( "SantaMonica");

// Add the land of Lincoln and the Windy City..
//
StateObj il = usa.Add( "Illinois");
il.Add( "Chicago");

// Give me something to write to (this will be UTF-16, but you can
// always serialize to another intermediary using UTF-8 encoding
// as your example XML presupposes).
//
StringBuilder buf = new StringBuilder( 1024);
StringWriter sw = new StringWriter( buf);

// Serialize the above StateCollection to XML in a string.
//
XmlSerializer ser = new XmlSerializer( typeof( StateCollection));
ser.Serialize( sw, usa);
sw.Flush( );

// Display results.
//
string xml = buf.ToString( );
Console.WriteLine( xml);

// Turn the string around into a Reader and then Deserialize it
// into a new instance of the StateCollection type.
//
StringReader sr = new StringReader( xml);
StateCollection eeuu = ser.Deserialize( sr) as StateCollection;
if ( null != eeuu )
{
// Did it deserialize successfully? (this was a property I impl'd above.)
//
Console.WriteLine( eeuu.IsOK);

// Loop through each State in this deserialized StateCollection.
//
foreach( StateObj st in eeuu)
{
Console.WriteLine( st.StateName);

// Loop through each City in this deserialized State.
//
foreach( CityObj city in st)
{
Console.WriteLine( "\t" + city.City);
}
}
}
}
}
- - -

When you run this you'll observe the following XML is generated by
the WriteXml( ) method,

- - - state.xml
<?xml version="1.0" encoding="utf-16"?>
<StateCollection>
<State xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.o
rg/2001/XMLSchema-instance">
<California>
<City>
<LosAngeles>
</LosAngeles>
<SantaMonica>
</SantaMonica>
</City>
</California>
<Illinois>
<City>
<Chicago>
</Chicago>
</City>
</Illinois>
</State>
</StateCollection>
- - -

The object model that's deserialized from this has the following structure,
matching what the test driver application originally created:

California
LosAngeles
SantaMonica
Illinois
Chicago
So, after all that, it is possible. Nevertheless, designing a schema in
which the local names of elements contain the information content of
the document, instead of describing it's structure, should be avoided.
Think of how much easier the following would've been to serialize (or
represent in an XML schema document):

- - - BetterStates.xml
<States>
<State name="California">
<City name="Los Angeles" />
<City name="Santa Monica" />
</State>
<State name="Illinois">
<City name="Chicago" />
</State>
</States>
- - -

In this schema, the elements and attribute names describe the structure,
and their values are the information content. Much more flexible and
adaptable, than the original solution (and it serializes more easily, too!). :-)
Derek Harmon
Nov 12 '05 #5

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

1 post views Thread by Stephen Edgecombe | last post: by
1 post views Thread by Shailendra Batham | last post: by
4 posts views Thread by pei_world | last post: by
1 post views Thread by Rob R. Ainscough | last post: by
reply views Thread by Saiars | last post: by
reply views Thread by leo001 | last post: by

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.