xmlns=''> was not expected.

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Shailendra Batham

    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>foo@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
  • Derek Harmon

    #2
    Re: xmlns=''&gt; was not expected.

    "Shailendra Batham" <sgbatham@sbcgl obal.net> wrote in message news:Fj9Yc.9143 $QJ3.8029@newss vr21.news.prodi gy.com...[color=blue]
    > 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[/color]
    : :[color=blue]
    > 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()[/color]

    The XML you are trying to deserialize looks like this,

    <InSession>
    <PassWord>foo </PassWord>
    <UserName>foo@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>foo@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


    Comment

    • Shailendra Batham

      #3
      Re: xmlns=''&gt; was not expected.

      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" <loresayer@msn. com> wrote in message
      news:%239ylFoXj EHA.3348@TK2MSF TNGP12.phx.gbl. ..[color=blue]
      > "Shailendra Batham" <sgbatham@sbcgl obal.net> wrote in message
      > news:Fj9Yc.9143 $QJ3.8029@newss vr21.news.prodi gy.com...[color=green]
      >> 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[/color]
      > : :[color=green]
      >> 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()[/color]
      >
      > The XML you are trying to deserialize looks like this,
      >
      > <InSession>
      > <PassWord>foo </PassWord>
      > <UserName>foo@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>foo@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
      >
      >[/color]


      Comment

      • Stronzo

        #4
        Re: xmlns=''&gt; was not expected.

        Apply XmlRoot attribute to your class:

        [XmlRoot("InSess ion")]public class cXmlBS{public String PassWord;public String UserName;}


        Comment

        • Derek Harmon

          #5
          Re: xmlns=''&gt; was not expected.

          "Shailendra Batham" <sgbatham@sbcgl obal.net> wrote in message news:uVoYc.1356 1$2%2.60@newssv r29.news.prodig y.com...[color=blue]
          > <?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.[/color]

          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


          Comment

          Working...