473,780 Members | 2,229 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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><UserN ame>fo*@foo.com </UserName></InSession>";Xml Serializer serializer = new XmlSerializer(t ypeof(cXmlBS)); XmlTextReader tr = new XmlTextReader(n ew System.IO.Strin gReader(xin));c XmlBS cx = (cXmlBS)seriali zer.Deserialize (tr);tr.Close() ;}public class cXmlBS{public String PassWord;public String UserName;}Syste m.InvalidOperat ionException: There is an error in XML document (1, 40). ---> System.InvalidO perationExcepti on: <InSession xmlns=''> was not expected.
at Microsoft.Xml.S erialization.Ge neratedAssembly .XmlSerializati onReader1.Read4 _cXmlBS()
--- End of inner exception stack trace ---
at System.Xml.Seri alization.XmlSe rializer.Deseri alize(XmlReader xmlReader, String encodingStyle)
at System.Xml.Seri alization.XmlSe rializer.Deseri alize(XmlReader xmlReader)
at BathamWS.LoginS ervice.BeginSes sion(String xin) in c:\inetpub\wwwr oot\bathamws\lo ginws.asmx.cs:l ine 62
help is appreciated, thanksshailendr a batham
Nov 12 '05 #1
4 59330
"Shailendra Batham" <sg******@sbcgl obal.net> wrote in message news:Fj******** *********@newss vr21.news.prodi gy.com...
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.InvalidO perationExcepti on: There is an error in XML document (1, 40).
---> System.InvalidO perationExcepti on: <InSession xmlns=''> was not expected.
at Microsoft.Xml.S erialization.Ge neratedAssembly .XmlSerializati onReader1.Read4 _cXmlBS()


The XML you are trying to deserialize looks like this,

<InSession>
<PassWord>foo </PassWord>
<UserName>fo*@f oo.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 InvalidOperatio nException 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*@f oo.com</UserName>
</cXmlBS>

or you can decorate the class/type name with an XmlRootAttribut e 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******** ********@TK2MSF TNGP12.phx.gbl. ..
"Shailendra Batham" <sg******@sbcgl obal.net> wrote in message
news:Fj******** *********@newss vr21.news.prodi gy.com...
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.InvalidO perationExcepti on: There is an error in XML document (1,
40).
---> System.InvalidO perationExcepti on: <InSession xmlns=''> was not
expected.
at
Microsoft.Xml.S erialization.Ge neratedAssembly .XmlSerializati onReader1.Read4 _cXmlBS()


The XML you are trying to deserialize looks like this,

<InSession>
<PassWord>foo </PassWord>
<UserName>fo*@f oo.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 InvalidOperatio nException 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*@f oo.com</UserName>
</cXmlBS>

or you can decorate the class/type name with an XmlRootAttribut e 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("InSess ion")]public class cXmlBS{public String PassWord;public String UserName;}
Nov 12 '05 #4
"Shailendra Batham" <sg******@sbcgl obal.net> wrote in message news:uV******** ********@newssv r29.news.prodig y.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 IXmlSerializabl e 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.Collecti ons;
using System.Diagnost ics;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Sche ma;
using System.Xml.Seri alization;

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.A dd( city);
return city;
}

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

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

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

public bool IsOK
{
get
{
return this.deserializ edOK;
}
}

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.Get Enumerator( )
{
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 IXmlSerializabl e 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:complexTy pe name="StatesTyp e">
<xs:sequence>
<!-- Allow literally any content in the empty xmlns='' -->
<xs:any namespace="##lo cal" minOccurs="1" maxOccurs="unbo unded" />
</xs:sequence>
</xs:complexType>

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

</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 ValidationEvent Handler 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 ValidationEvent Handler
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 IXmlSerializabl e implementation) .

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

foreach( StateObj st in this )
{
writer.WriteSta rtElement( 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 WriteStartEleme nt( "City") and WriteEndElement () inside foreach
// loop and use a firstTimeOnly flag to write them.
//
writer.WriteSta rtElement( "City");
foreach( CityObj city in st)
{
writer.WriteSta rtElement( city.City);
writer.WriteFul lEndElement( );
}
writer.WriteFul lEndElement( ); // </City>

writer.WriteFul lEndElement(); // </StateName>
}

writer.WriteEnd Element(); // </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 (betweenStateAn dCity == 1) and city names after a <City>
are the greatest depth (betweenStateAn dCity == 3).

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

try
{
StateObj currentState = null;
while ( reader.Read( ) && !reachedEnd )
{
if ( reader.IsStartE lement( ) )
{
string name = reader.LocalNam e;
hopper.Push( name);

if ( 0 == name.CompareTo( "State"))
{
++betweenStateA ndCity;
}
else if ( 0 == name.CompareTo( "City"))
{
++betweenStateA ndCity;
}
else if ( ( 2 == betweenStateAnd City ) && ( null == currentState ) )
{
currentState = new StateObj( name);
}
else if ( ( 3 == betweenStateAnd City ) && ( null != currentState ) )
{
currentState.Ad d( name);
}
Debug.WriteLine ( "pushed {0}", name);
}
else if ( reader.NodeType == XmlNodeType.End Element )
{
if ( hopper.Count > 0 )
{
string name = hopper.Pop( ) as string;
if ( 0 == name.CompareTo( "City"))
{
this.Add( currentState);
currentState = null;
--betweenStateAnd City;
}
if ( 0 == name.CompareTo( "State"))
{
reachedEnd = true;
--betweenStateAnd City;
}
Debug.WriteLine ( "popped {0}", (name == null)? "(null)": name);
}
}
}
}
catch ( XmlException xe)
{
Debug.WriteLine ( xe.Message);
this.deserializ edOK = 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
IXmlSerializabl e 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( "SantaMonic a");

// 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.WriteLi ne( 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.WriteLi ne( eeuu.IsOK);

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

// Loop through each City in this deserialized State.
//
foreach( CityObj city in st)
{
Console.WriteLi ne( "\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"?>
<StateCollectio n>
<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.xm l
<States>
<State name="Californi a">
<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 thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
5359
by: Julia | last post by:
Hi,i am trying to DeSerialize the following class from an XML string and i get "<root xmlns=''> was not expected." public class Person { private string m_Name; private string m_Phone; public Person() {
1
4335
by: Stephen Edgecombe | last post by:
Hi Environment: Visual Studio .NET 2003 (vb) I am developing an XSD Schema and want to include some building blocks from another source, so they have a different namespace. - If I use an <Include> the Schema doesn't show any of the Elements from the include Schema. But that's to be expected because they are in a different namespace. - If I use <Import> the Schema doesn't show any of the Elements from the
1
9584
by: Shailendra Batham | last post by:
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>foo@foo.com</UserName></InSession>";XmlSerializer serializer = new XmlSerializer(typeof(cXmlBS));XmlTextReader tr = new XmlTextReader(new System.IO.StringReader(xin));cXmlBS cx =...
4
2967
by: pei_world | last post by:
I have followed a example from a book exactly, but it seems not working at all. can anyone tell me what is going on? ========= Global.asax.cs ============ public static Entry LoadEntry(String filename) { //construct the path
1
4618
by: Rob R. Ainscough | last post by:
I'm using XmlSerializer to read the an XML file into an object collection. As soon as I .Deserialize(myFileStream) I get the above error: my XML looks like <?xml version="1.0" encoding="UTF-8"?> <dataroot xmlns:od="urn:schemas-microsoft-com:officedata" generated="2006-06-09T14:07:13"> <Applications> <ApplicationID>0</ApplicationID>
2
12625
by: snowie | last post by:
I have a simillar problem to what others have had before me. I just can't find the solution in any earlier post here at the scripts (or any other forum). I am calling a web service that returns a string, the string is an object serialized into XML. The XML returned could look like: ...
2
2567
by: aglaforge | last post by:
I'm attempting to write a quick piece of Javascript code that will validate if the end user of the javascript has the necessary VML attributes set in their HTML. The problem in IE is that "xmlns:v" does not appear in their attributes property or the getAttribute('xmlns:v') calls. The real kicker is that the 'xmlns' attribute does return something. The HTML Snippet would look like this: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0...
1
4314
by: ismailc | last post by:
Hi, I need help please. Update system to to new version & moved on to .Net2 But now my code that worked in my .Net1 xslt does not work. .Net1 fine: <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0" xmlns:asp="remove" xmlns:igchart="remove" xmlns:igsch="remove"> &lt;td class='rowDet' id="td_<xsl:value-of select='@name' />"&gt; .Net2 don't work: <xsl:stylesheet...
1
4255
by: nwbabcock | last post by:
I'm using XmlSerializer to deserialize an xml into classes. The error I recieve is: Exception:There is an error in XML document (2, 2). Inner Exception: <applications xmlns='urn:xmlns:COMMONCENSUS:CommonFormat:IMSchema'> was not expected. I've read numerous threads on this but none seem to help with this particular issue. I've included the xml, and the Schema file below as well as the code. First post also, so I'm not sure how to add the...
0
9636
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9474
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10139
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8961
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7485
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5373
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5504
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4037
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2869
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.