Append to a file using XML Serialization? Easy way to do this?

Discussion in 'XML' started by RayLopez99, Jul 20, 2009.

  1. RayLopez99

    RayLopez99 Guest

    Is there an easy way to do this? Without using style sheet filters,
    etc? I have a decorated class (uses [XmlRoot], [XmlAttribute], etc)
    but I can only add one node at a time when I create the XML file--but
    I want to add more than one node, however I get an error if you add
    more than one node (error: cannot form XML).

    If there's a short way to fix this please let me know. I think I can
    fix it using DOM and the "long or hard way", by writing and reading
    each node individually from a List (I've done this before). But I'm
    trying to do this the "short or easy way" using XML Serialization.

    Thank you

    RL

    //Here is the code: self explanitory, two Decorated class nodes being
    added, myDecPerson1 ("Rob1 Smith") and myDecPerson1 ("Rob2 Smith2")
    // Discussion on stripping out top element here: //
    http://www.csharper.net/blog/serializing_without_the_namespace__xmlns__xmlns_xsd__xmlns_xsi_.aspx

    protected void cmd_Button1_Click(Object sender, EventArgs e)
    {
    DecoratedPerson myDecPerson1 = new DecoratedPerson();
    myDecPerson1.FirstName = "Rob1";
    myDecPerson1.LastName = "Smith1";
    myDecPerson1.Password = "SecretSmith";
    myDecPerson1.Email = "";
    myDecPerson1.Age = int.Parse("99");
    myDecPerson1.UserId = "Rob1Smith";
    Guid myGuid = new Guid();
    myGuid = System.Guid.NewGuid();
    myDecPerson1.UserGuid = myGuid;
    // add to List
    myDecPersonList.Add(myDecPerson1);

    // now do second person, and add to list--fails!...

    DecoratedPerson myDecPerson2 = new DecoratedPerson();

    myDecPerson2.FirstName = "Rob2";
    myDecPerson2.LastName = "Smith2";
    myDecPerson2.Password = "SecretSmith2";
    myDecPerson2.Email = "";
    myDecPerson2.Age = int.Parse("88");
    myDecPerson2.UserId = "Rob2Smith";
    myGuid = new Guid();
    myGuid = System.Guid.NewGuid();
    myDecPerson2.UserGuid = myGuid;
    myDecPersonList.Add(myDecPerson2);

    //create file and add nodes ..

    string totalFilepath = Path.Combine
    (Request.PhysicalApplicationPath, @"App_Data
    \XMLPasswordDoc77.xml"); //create path
    XmlSerializerNamespaces ns = new XmlSerializerNamespaces
    ();

    ns.Add("mytest", "http://www.w3.org/2001/XMLSchemaMyOwn");

    XmlWriterSettings settings = new XmlWriterSettings();
    settings.OmitXmlDeclaration = false; // Don't remove the
    <?xml version="1.0" encoding="utf-8"?>

    XmlWriter writer = XmlWriter.Create(totalFilepath,
    settings);


    XmlSerializer serializer = new XmlSerializer(typeof
    (DecoratedPerson));

    foreach (DecoratedPerson p in myDecPersonList)
    {

    serializer.Serialize(writer, p, ns); //only works w/o
    exception if only one element in list! if > 1 fails!
    }

    writer.Close();




    } //end of method


    //OUTPUT (works if only one node in List):


    //
    <?xml version="1.0" encoding="utf-8" ?>
    - <MyEmployee xmlns:mytest="http://www.w3.org/2001/XMLSchemaMyOwn"
    GUID="665ae831-275e-427b-9737-9f3856c8c84a">
    <FiRstName>Rob1</FiRstName>
    <lAsTNaMe>Smith1</lAsTNaMe>
    <pAssworD>SecretSmith</pAssworD>
    <eeemaiL></eeemaiL>
    <Age>99</Age>
    <UserId>Rob1Smith</UserId>
    </MyEmployee>



    // but error if you add more than one node (cannot form XML)

    //Here is the decorated class...
    [XmlRoot(ElementName="MyEmployee")]
    public class DecoratedPerson
    {
    private string firstName;
    private string lastName;
    private string password;
    private string email;
    private int age;
    private Guid userGuid;
    private string userId;

    [XmlElement(ElementName="FiRstName")]
    public string FirstName
    {
    get
    {
    return firstName;

    }
    set
    {
    firstName = value;
    }
    }

    [XmlElement(ElementName="lAsTNaMe")]
    public string LastName
    {
    get
    {
    return lastName;

    }
    set
    {
    lastName = value;
    }
    }

    [XmlElement(ElementName = "pAssworD")]
    public string Password
    {
    get
    {
    return password;

    }
    set
    {
    password = value;
    }
    }

    [XmlElement(ElementName = "eeemaiL")]
    public string Email
    {
    get
    {
    return email;

    }
    set
    {
    email = value;
    }
    }

    [XmlElement(IsNullable=false)]
    public int Age
    {
    get
    {
    return age;

    }
    set
    {
    age = value;
    }
    }

    [XmlAttribute(AttributeName="GUID")]
    public Guid UserGuid
    {
    get
    {
    return userGuid;

    }
    set
    {
    userGuid = value;
    }
    }

    [XmlElement(IsNullable = true)]
    public string UserId
    {
    get
    {
    return userId;

    }
    set
    {
    userId = value;
    }
    }


    public DecoratedPerson()
    {

    }
    }
     
    RayLopez99, Jul 20, 2009
    #1
    1. Advertising

  2. RayLopez99 wrote:

    > DecoratedPerson myDecPerson1 = new DecoratedPerson();
    > myDecPerson1.FirstName = "Rob1";
    > myDecPerson1.LastName = "Smith1";
    > myDecPerson1.Password = "SecretSmith";
    > myDecPerson1.Email = "";
    > myDecPerson1.Age = int.Parse("99");
    > myDecPerson1.UserId = "Rob1Smith";
    > Guid myGuid = new Guid();
    > myGuid = System.Guid.NewGuid();
    > myDecPerson1.UserGuid = myGuid;
    > // add to List
    > myDecPersonList.Add(myDecPerson1);
    >
    > // now do second person, and add to list--fails!...
    >
    > DecoratedPerson myDecPerson2 = new DecoratedPerson();
    >
    > myDecPerson2.FirstName = "Rob2";
    > myDecPerson2.LastName = "Smith2";
    > myDecPerson2.Password = "SecretSmith2";
    > myDecPerson2.Email = "";
    > myDecPerson2.Age = int.Parse("88");
    > myDecPerson2.UserId = "Rob2Smith";
    > myGuid = new Guid();
    > myGuid = System.Guid.NewGuid();
    > myDecPerson2.UserGuid = myGuid;
    > myDecPersonList.Add(myDecPerson2);
    >
    > //create file and add nodes ..
    >
    > string totalFilepath = Path.Combine
    > (Request.PhysicalApplicationPath, @"App_Data
    > \XMLPasswordDoc77.xml"); //create path
    > XmlSerializerNamespaces ns = new XmlSerializerNamespaces
    > ();
    >
    > ns.Add("mytest", "http://www.w3.org/2001/XMLSchemaMyOwn");
    >
    > XmlWriterSettings settings = new XmlWriterSettings();
    > settings.OmitXmlDeclaration = false; // Don't remove the
    > <?xml version="1.0" encoding="utf-8"?>
    >
    > XmlWriter writer = XmlWriter.Create(totalFilepath,
    > settings);
    >
    >
    > XmlSerializer serializer = new XmlSerializer(typeof
    > (DecoratedPerson));
    >
    > foreach (DecoratedPerson p in myDecPersonList)
    > {
    >
    > serializer.Serialize(writer, p, ns); //only works w/o
    > exception if only one element in list! if > 1 fails!
    > }
    >
    > writer.Close();
    >
    >
    >
    >
    > } //end of method


    The .NET framework allows you to create an XML fragment by setting
    settings.ConformanceLevel = ConformanceLevel.Fragment;
    on your XmlWriterSettings variable. That way you should be able to write
    out serveral DecoratedPerson elements. You should however be aware that
    you can't read the generated XML with XmlDocument or XDocument as these
    implement the W3C specification for well-formed XML documents to have
    exactly one root element that contains all other elements.
    XmlReader on the other hand can also be set in "fragment mode" with an
    XmlReaderSettings instance and the same ConformanceLevel setting.

    --

    Martin Honnen
    http://msmvps.com/blogs/martin_honnen/
     
    Martin Honnen, Jul 20, 2009
    #2
    1. Advertising

  3. RayLopez99

    RayLopez99 Guest

    Re: Append to a file using XML Serialization? Easy way to do this?

    On Jul 20, 5:39 am, Martin Honnen <> wrote:
    >
    > The .NET framework allows you to create an XML fragment by setting
    >    settings.ConformanceLevel = ConformanceLevel.Fragment;
    > on your XmlWriterSettings variable. That way you should be able to write
    > out serveral DecoratedPerson elements. You should however be aware that
    > you can't read the generated XML with XmlDocument or XDocument as these
    > implement the W3C specification for well-formed XML documents to have
    > exactly one root element that contains all other elements.
    > XmlReader on the other hand can also be set in "fragment mode" with an
    > XmlReaderSettings instance and the same ConformanceLevel setting.
    >


    I thank you for your time. I am able to generate fragments, but like
    you say they miss the "exactly one root element".

    Can you post, in pseudo-code or words, how to generate a root element
    programically once you have nodes (fragments)?

    Let's say you have these node fragments:

    <Person>
    <FirstName> joe </FirstName>
    <LastName> smith </LastName>
    </Person>

    <Person>
    <FirstName> Sam </FirstName>
    <LastName> Miller </LastName>
    </Person>

    In one file, now how can you add a root element in an easy way?

    Such as

    <?xml version="1.0" ?>
    <MyRootElementHere>

    // above 2 nodes go here

    </MyRootElementHere>

    I can do this the "hard way" by mechanically inserting text into
    another text file, but I'm wondering if there's a quick way to convert
    fragments into well formed XML documents (there should be--this must
    be a reoccuring common problem).

    Unless there is an easy way to do this, I am going back to using DOM
    and "TextWriter", etc, node by node, which at least I am able to form
    well formed XML documents (but it's tedious to do).

    RL
     
    RayLopez99, Jul 20, 2009
    #3
  4. Re: Append to a file using XML Serialization? Easy way to do this?

    RayLopez99 wrote:

    > Can you post, in pseudo-code or words, how to generate a root element
    > programically once you have nodes (fragments)?


    Why "once you have nodes"? Why can't you simply write out the root
    element with your XmlWriter with writer.WriteStartElement("root") and
    then pass on that writer to your XmlSerializer?


    > In one file, now how can you add a root element in an easy way?
    >
    > Such as
    >
    > <?xml version="1.0" ?>
    > <MyRootElementHere>
    >
    > // above 2 nodes go here
    >
    > </MyRootElementHere>


    XInclude (http://www.w3.org/TR/xinclude/) is a way to include stuff in
    XML but Microsoft does not support XInclude with its XML parsers. And I
    am currently not sure it would allow you include a fragment.

    The ConformanceLevel.Fragment exists as an implementation of what the
    XML specification calls "external parsed entity"
    (http://www.w3.org/TR/xml/#NT-extParsedEnt). So to use that you need a
    DTD that defines an external entity and then you can reference that
    entity in your document:

    <!DOCTYPE root [
    <!ENTITY foo SYSTEM "XMLFile2.xml">
    ]>
    <root>
    &foo;
    </root>

    where XMLFile2.xml then can look like this:

    <?xml version="1.0" encoding="utf-8" ?>
    <foo>1</foo>
    <foo>2</foo>
    <foo>3</foo>

    To parse the main file with XmlReader and .NET 2.0 or later you need e.g.

    XmlReaderSettings settings = new XmlReaderSettings();
    settings.ProhibitDtd = false;
    using (XmlReader reader = XmlReader.Create(@"XMLFile1.xml",
    settings))
    {
    while (reader.Read())
    {
    // access stuff here
    }
    }

    --

    Martin Honnen
    http://msmvps.com/blogs/martin_honnen/
     
    Martin Honnen, Jul 20, 2009
    #4
  5. RayLopez99

    RayLopez99 Guest

    Re: Append to a file using XML Serialization? Easy way to do this?

    On Jul 20, 11:20 am, Martin Honnen <> wrote:
    > RayLopez99 wrote:
    > > Can you post, in pseudo-code or words, how to generate a root element
    > > programically once you have nodes (fragments)?

    >
    > Why "once you have nodes"? Why can't you simply write out the root
    > element with your XmlWriter with writer.WriteStartElement("root") and
    > then pass on that writer to your XmlSerializer?


    Martin Honnen - thank you! I fixed it, using your suggestion above.
    For my problem it was trivial--see the post below at //IMPORTANT-MUST
    ADD! Adding these two lines for the Root Element (.WriteStartElement)
    allowed me to add as many nodes as I want from my List.

    Thanks again. The rest of your post I did not understand but for my
    purposes I'm finished with this problem.

    RL

    // program same as original post except for the below...

    string totalFilepath = Path.Combine
    (Request.PhysicalApplicationPath, @"App_Data
    \XMLPasswordDoc77.xml"); //create path
    XmlSerializerNamespaces ns = new XmlSerializerNamespaces
    ();
    //ns.Add("", "");
    ns.Add("mytest", "http://www.w3.org/2001/XMLSchemaMyOwn");

    XmlWriterSettings settings = new XmlWriterSettings();
    settings.OmitXmlDeclaration = false; // do not Remove the
    <?xml version="1.0" encoding="utf-8"?>

    XmlWriter writer = XmlWriter.Create(totalFilepath,
    settings);
    writer.WriteStartElement("ARootElement"); //IMPORTANT-
    MUST ADD!


    XmlSerializer serializer = new XmlSerializer(typeof
    (DecoratedPerson));
    foreach (DecoratedPerson p in myDecPersonList)
    {

    serializer.Serialize(writer, p, ns); //now you can,
    using Martin's suggestion, write as many nodes from the List
    myDecPersonList as you want--not limited to one node.
    }

    writer.WriteEndElement();//IMPORTANT-MUST ADD!


    writer.Close();
     
    RayLopez99, Jul 20, 2009
    #5
  6. RayLopez99

    RayLopez99 Guest

    Re: Append to a file using XML Serialization? Easy way to do this?

    Also does anybody know if there is a 'easier' (or cleaner, less code
    required) way of deserializing than checking each node as per the
    below code?

    RL

    //as inspired by: http://support.microsoft.com/kb/307548

    private string ReadXMLandAddtoDecoratedPersonList(string filepath)
    {
    string statusStr = "Success
    ReadXMLandAddtoDecoratedPersonList";

    try
    {
    using (FileStream fs = new FileStream(filepath,
    FileMode.Open))
    {
    using (XmlTextReader r = new XmlTextReader(fs))

    {
    myDecPersonList.Clear();

    DecoratedPerson newDecPerson1 = new
    DecoratedPerson();
    while (r.Read())
    {
    Debug.WriteLine("r.Read element is: " +
    r.NodeType.ToString() + "(type)" + "," + r.ValueType.ToString() +
    " (value type)" + "," + r.Value.ToString() + "(value)" + "," +
    r.Name.ToString() + "Name!");
    if (r.NodeType == XmlNodeType.Element &&
    r.Name == "MyEmployee")
    {

    string aStringGuid = r.GetAttribute
    (1);//gets Second attribute, which is GUID (.GetAttribute(0) is
    schema)
    Debug.WriteLine("this is MyEmployee
    attribute: " + aStringGuid);
    newDecPerson1.UserGuid = new Guid
    (aStringGuid);

    }
    if (r.NodeType == XmlNodeType.Element &&
    r.Name == "FiRstName")
    {
    r.Read(); // req'd to push to next
    element
    if (r.NodeType == XmlNodeType.Text)
    {
    newDecPerson1.FirstName = r.Value;
    Debug.WriteLine("r.Read element
    FirstName is: " + r.NodeType.ToString() + "(type)" + "," +
    r.ValueType.ToString() + " (value type)" + "," + r.Value.ToString() +
    "(value)");

    }
    }

    if (r.NodeType == XmlNodeType.Element &&
    r.Name == "LAsTNaMe")
    {
    r.Read(); //!! req'd to push to next
    element
    if (r.NodeType == XmlNodeType.Text)
    {
    newDecPerson1.LastName = r.Value;
    Debug.WriteLine("r.Read element
    LastName is: " + r.NodeType.ToString() + "(type)" + "," +
    r.ValueType.ToString() + " (value type)" + "," + r.Value.ToString() +
    "(value)");

    }
    }

    if (r.NodeType == XmlNodeType.Element &&
    r.Name == "thePassword")
    {
    r.Read(); //!! req'd to push to next
    element
    if (r.NodeType == XmlNodeType.Text)
    {
    newDecPerson1.Password = r.Value;
    Debug.WriteLine("r.Read element
    Password is: " + r.NodeType.ToString() + "(type)" + "," +
    r.ValueType.ToString() + " (value type)" + "," + r.Value.ToString() +
    "(value)");

    }
    }

    if (r.NodeType == XmlNodeType.Element &&
    r.Name == "theEmaiL")
    {
    r.Read(); //!! req'd to push to next
    element
    if (r.NodeType == XmlNodeType.Text)
    {
    newDecPerson1.Email = r.Value;
    Debug.WriteLine("r.Read element
    Email is: " + r.NodeType.ToString() + "(type)" + "," +
    r.ValueType.ToString() + " (value type)" + "," + r.Value.ToString() +
    "(value)");

    }
    }

    if (r.NodeType == XmlNodeType.Element &&
    r.Name == "Age")
    {
    r.Read(); //!! req'd to push to next
    element
    if (r.NodeType == XmlNodeType.Text)
    {
    try
    {
    newDecPerson1.Age =
    Convert.ToInt32(r.Value);
    Debug.WriteLine("r.Read
    element Age is: " + r.NodeType.ToString() + "(type)" + "," +
    r.ValueType.ToString() + " (value type)" + "," + r.Value.ToString() +
    "(value)");


    }
    catch (FormatException)
    {
    Debug.WriteLine("The Age did
    not convert: default zero used");
    newDecPerson1.Age = 0;
    }


    }
    }

    if (r.NodeType == XmlNodeType.Element &&
    r.Name == "UserId")
    {
    r.Read(); //!! req'd to push to next
    element
    if (r.NodeType == XmlNodeType.Text)
    {
    newDecPerson1.UserId = r.Value;
    Debug.WriteLine("r.Read element
    UserId is: " + r.NodeType.ToString() + "(type)" + "," +
    r.ValueType.ToString() + " (value type)" + "," + r.Value.ToString() +
    "(value)");

    }
    }

    if ((newDecPerson1.FirstName !=
    String.Empty) && (newDecPerson1.LastName != String.Empty) &&
    (newDecPerson1.Password != String.Empty) && (newDecPerson1.Email !=
    String.Empty) && (newDecPerson1.Age != -1) && (newDecPerson1.UserId !
    = String.Empty))
    {
    //add new person to the list and
    create a new newDecPerson
    myDecPersonList.Add(newDecPerson1);
    Debug.WriteLine("now adding a
    DecoratedPerson comprising...");
    Debug.WriteLine
    (newDecPerson1.FirstName + "," + newDecPerson1.LastName + "," +
    newDecPerson1.Password + "," + newDecPerson1.Email + "," +
    newDecPerson1.Age.ToString() + "," + newDecPerson1.UserId);
    newDecPerson1 = new DecoratedPerson
    (); //re-instantiate a new object, since old one added to List.

    }


    }

    }

    }
    }
    catch (FileNotFoundException fNF)
    {
    Debug.WriteLine(fNF.Message);
    statusStr = fNF.Message;
    }
    catch (Exception ex)
    {
    Debug.WriteLine(ex.Message);
    statusStr = ex.Message;
    }

    finally
    {
    ////debug output: works fine, as expected
    foreach (DecoratedPerson p in myDecPersonList)
    {
    Debug.WriteLine("these values exist for p: " +
    p.LastName + "," + p.FirstName + "," + p.Password + "," + p.Email +
    "," + p.Age.ToString() + "," + p.UserId + "," + p.UserGuid);
    }

    }

    return statusStr;

    }
     
    RayLopez99, Jul 20, 2009
    #6
  7. Re: Append to a file using XML Serialization? Easy way to do this?

    RayLopez99 wrote:
    > Also does anybody know if there is a 'easier' (or cleaner, less code
    > required) way of deserializing than checking each node as per the
    > below code?


    Yes, certainly, see this example:

    class Program
    {
    static void Main(string[] args)
    {
    List<Foo> foos = new List<Foo>()
    {
    new Foo() { Bar = "bar 1", Baz = 1 },
    new Foo() { Bar = "bar 2", Baz = 2 },
    new Foo() { Bar = "bar 3", Baz = 3 }
    };

    XmlWriterSettings xrs = new XmlWriterSettings();
    xrs.Indent = true;
    XmlSerializer ser = new XmlSerializer(typeof(Foo));
    using (XmlWriter xr =
    XmlWriter.Create(@"..\..\XMLSer1.xml", xrs))
    {
    xr.WriteStartDocument();
    xr.WriteStartElement("Root");
    foreach (Foo foo in foos)
    {
    ser.Serialize(xr, foo);
    }
    xr.WriteEndElement();
    xr.WriteEndDocument();
    xr.Close();
    }

    List<Foo> foos2 = new List<Foo>();
    using (XmlReader xr = XmlReader.Create(@"..\..\XMLSer1.xml"))
    {
    while (xr.Read())
    {
    if (xr.NodeType == XmlNodeType.Element && xr.Name
    == "Foo")
    {
    Foo foo = (Foo)ser.Deserialize(xr);
    foos2.Add(foo);
    }
    }
    xr.Close();
    }

    foreach (Foo foo in foos2)
    {
    Console.WriteLine("Bar: {0}; Baz: {1}", foo.Bar, foo.Baz);
    }
    }
    }

    public class Foo
    {
    public string Bar { get; set; }
    public int Baz { get; set; }
    }


    So you simply read through the file with an XmlReader's
    while(reader.Read()) loop and each time the reader is positioned on an
    element you are interested in you pass the reader to the Deserialize method.


    --

    Martin Honnen
    http://msmvps.com/blogs/martin_honnen/
     
    Martin Honnen, Jul 21, 2009
    #7
  8. RayLopez99

    RayLopez99 Guest

    Re: Append to a file using XML Serialization? Easy way to do this?

    On Jul 21, 6:18 am, Martin Honnen <> wrote:
    > RayLopez99 wrote:
    > >  Also does anybody know if there is a 'easier' (or cleaner, less code
    > > required) way of deserializing than checking each node as per the
    > > below code?

    >
    > Yes, certainly, see this example:
    >
    >      class Program
    >      {
    >          static void Main(string[] args)
    >          {
    >              List<Foo> foos = new List<Foo>()
    >              {
    >                  new Foo() { Bar = "bar 1", Baz = 1 },
    >                  new Foo() { Bar = "bar 2", Baz = 2 },
    >                  new Foo() { Bar = "bar 3", Baz = 3 }
    >              };
    >
    >              XmlWriterSettings xrs = new XmlWriterSettings();
    >              xrs.Indent = true;
    >              XmlSerializer ser = new XmlSerializer(typeof(Foo));
    >              using (XmlWriter xr =
    > XmlWriter.Create(@"..\..\XMLSer1.xml", xrs))
    >              {
    >                  xr.WriteStartDocument();
    >                  xr.WriteStartElement("Root");
    >                  foreach (Foo foo in foos)
    >                  {
    >                      ser.Serialize(xr, foo);
    >                  }
    >                  xr.WriteEndElement();
    >                  xr.WriteEndDocument();
    >                  xr.Close();
    >              }
    >
    >              List<Foo> foos2 = new List<Foo>();
    >              using (XmlReader xr = XmlReader.Create(@"..\...\XMLSer1.xml"))
    >              {
    >                  while (xr.Read())
    >                  {
    >                      if (xr.NodeType == XmlNodeType.Element && xr.Name
    > == "Foo")
    >                      {
    >                          Foo foo = (Foo)ser.Deserialize(xr);
    >                          foos2.Add(foo);
    >                      }
    >                  }
    >                  xr.Close();
    >              }
    >
    >              foreach (Foo foo in foos2)
    >              {
    >                  Console.WriteLine("Bar: {0}; Baz: {1}", foo.Bar, foo.Baz);
    >              }
    >          }
    >      }
    >
    >      public class Foo
    >      {
    >          public string Bar { get; set; }
    >          public int Baz { get; set; }
    >      }
    >
    > So you simply read through the file with an XmlReader's
    > while(reader.Read()) loop and each time the reader is positioned on an
    > element you are interested in you pass the reader to the Deserialize method.
    >
    > --


    I thank you for your time.

    However, I found a mistake in your code that I cannot overcome.

    Here it is:  

    if (xr.NodeType == XmlNodeType.Element && xr.Name == "Foo")

    I believe what happens here, from what I can tell, is that xr.Name
    == "Foo" is never triggered (never true). What you get is xr.Name ==
    Bar or xr.Name ==Baz.

    Can you double check this? If in fact it's what I find, this is
    identical to the "long" code I posted, which is a series of switch/
    case statements, which is no shorter than the code I posted in my
    previous post.

    I will try again with your code tommorrow.

    RL
     
    RayLopez99, Jul 23, 2009
    #8
  9. Re: Append to a file using XML Serialization? Easy way to do this?

    RayLopez99 wrote:

    > However, I found a mistake in your code that I cannot overcome.
    >
    > Here it is:
    >
    > if (xr.NodeType == XmlNodeType.Element && xr.Name == "Foo")
    >
    > I believe what happens here, from what I can tell, is that xr.Name
    > == "Foo" is never triggered (never true). What you get is xr.Name ==
    > Bar or xr.Name ==Baz.


    For me that sample successfully serializes and deserializes so I have no
    idea why you say it contains a mistake and does not find "Foo" elements.


    --

    Martin Honnen
    http://msmvps.com/blogs/martin_honnen/
     
    Martin Honnen, Jul 23, 2009
    #9
  10. RayLopez99

    RayLopez99 Guest

    Re: Append to a file using XML Serialization? Easy way to do this?

    On Jul 23, 5:56 am, Martin Honnen <> wrote:
    > For me that sample successfully serializes and deserializes so I have no
    > idea why you say it contains a mistake and does not find "Foo" elements.
    >
    >


    Hello Martin,

    I tried your program in Windows Console mode and it works, but I’m
    afraid it does not work for my more complicated class object being de-
    serialized.

    If you have any ideas why please post. Please don’t spend too much
    time as you have helped enough.

    I personally don’t care that I cannot get my program to work like
    yours, even though it would be an improvement, since my old, long way
    of checking each element, and de-serialising that element, though more
    time consuming, does work for me. However, it would be nice to
    deserialize the entire object “at once”, like is done in binary
    deserialization.

    //Here is the relevant code for deserializing. It does not work,
    since the condition xr.Name == “DecoratedPerson” is never reached.

    This code fragment appears to be failing: “if(xr.NodeType ==
    XmlNodeType.Element && xr.Name == "DecoratedPerson")”

    When I run the Debugger, the condition xr.Name == “DecoratedPerson” is
    never reached, because xr.Name is: “FiRstName” or “theEmaiL” or “Age”
    or “UserId”, etc. It is never "==DecoratedPerson"

    Consequently, the List is never populated and always has a count of
    zero, being empty.

    Thank you for your help.

    RL

    //Here is my “class object”, called DecoratedPerson, that is
    serialized in XML. I am attempting to de-serialize it with the code
    below.

    <?xml version="1.0" encoding="utf-8" ?>
    - <ARootElement>
    - <MyEmployee xmlns:mytest="http://www.w3.org/2001/XMLSchemaMyOwn"
    GUID="1f6aafa0-61ee-4f76-9935-d308299ff8bf">
    <FiRstName>Rob1</FiRstName>
    <LAsTNaMe>Smith1</LAsTNaMe>
    <thePassword>SecretSmith</thePassword>
    <theEmaiL></theEmaiL>
    <Age>19</Age>
    <UserId>Rob1Smith</UserId>
    </MyEmployee>
    - <MyEmployee xmlns:mytest="http://www.w3.org/2001/XMLSchemaMyOwn"
    GUID="2057ad4f-8511-4ec6-b7be-c9652571e407">
    <FiRstName>Rob2</FiRstName>
    <LAsTNaMe>Smith2</LAsTNaMe>
    <thePassword>SecretSmith2</thePassword>
    <theEmaiL></theEmaiL>
    <Age>18</Age>
    <UserId>Rob2Smith</UserId>
    </MyEmployee>
    - <MyEmployee xmlns:mytest="http://www.w3.org/2001/XMLSchemaMyOwn"
    GUID="325e0a07-329d-4544-ba36-e79abe2cbc6b">
    <FiRstName>Rob3</FiRstName>
    <LAsTNaMe>Smith3</LAsTNaMe>
    <thePassword>SecretSmith3</thePassword>
    <theEmaiL></theEmaiL>
    <Age>33</Age>
    <UserId>Rob3Smith</UserId>
    </MyEmployee>
    </ARootElement>

    //Here is the relevant code for deserializing the above. It does not
    work, since the condition xr.Name == “DecoratedPerson” is never
    reached.

    This code fragment appears to be failing: “if(xr.NodeType ==
    XmlNodeType.Element && xr.Name == "DecoratedPerson")”

    When I run the Debugger, the condition xr.Name == “DecoratedPerson” is
    never reached, because xr.Name is: “FiRstName” or “theEmaiL” or “Age”
    or “UserId”, etc. It is never "==DecoratedPerson"

    Consequently, the List is never populated and always has a count of
    zero, being empty.

    RL

    protected void cmd_Button3_Click(Object sender, EventArgs e)
    {
    string totalFilepath = Path.Combine
    (Request.PhysicalApplicationPath, @"App_Data
    \XMLPasswordDocManyNodes.xml"); //create path
    this.ReadXMLandAddtoDecoratedPersonList2(totalFilepath);
    }

    private string ReadXMLandAddtoDecoratedPersonList2(string
    filepath)
    {
    string statusStr = "Success
    ReadXMLandAddtoDecoratedPersonList2";

    try
    {
    using (XmlReader xr = XmlReader.Create(filepath))
    {
    XmlSerializer ser = new XmlSerializer(typeof
    (DecoratedPerson));

    myDecPersonList.Clear();
    while (xr.Read())
    {
    if(xr.NodeType == XmlNodeType.Element &&
    xr.Name == "DecoratedPerson") ///!!!
    {
    DecoratedPerson foo = (DecoratedPerson)
    ser.Deserialize(xr);
    myDecPersonList.Add(foo);
    }



    }
    xr.Close();
    }
    }
    catch (FileNotFoundException fNF)
    {
    Debug.WriteLine(fNF.Message);
    statusStr = fNF.Message;
    }
    catch (Exception ex)
    {
    Debug.WriteLine(ex.Message);
    statusStr = ex.Message;
    }

    finally
    {

    int j = myDecPersonList.Count;
    Debug.WriteLine("count is: " + j.ToString());
    foreach (DecoratedPerson p in myDecPersonList)
    {
    Debug.WriteLine("these values exist for
    DecoratedPerson!: " + p.LastName + "," + p.FirstName + "," +
    p.Password + "," + p.Email + "," + p.Age.ToString() + "," + p.UserId +
    "," + p.UserGuid);
    }

    }

    return statusStr;

    }
     
    RayLopez99, Jul 23, 2009
    #10
  11. Re: Append to a file using XML Serialization? Easy way to do this?

    RayLopez99 wrote:

    > //Here is my “class object”, called DecoratedPerson, that is
    > serialized in XML. I am attempting to de-serialize it with the code
    > below.
    >
    > <?xml version="1.0" encoding="utf-8" ?>
    > - <ARootElement>
    > - <MyEmployee xmlns:mytest="http://www.w3.org/2001/XMLSchemaMyOwn"
    > GUID="1f6aafa0-61ee-4f76-9935-d308299ff8bf">
    > <FiRstName>Rob1</FiRstName>
    > <LAsTNaMe>Smith1</LAsTNaMe>
    > <thePassword>SecretSmith</thePassword>
    > <theEmaiL></theEmaiL>
    > <Age>19</Age>
    > <UserId>Rob1Smith</UserId>
    > </MyEmployee>
    > - <MyEmployee xmlns:mytest="http://www.w3.org/2001/XMLSchemaMyOwn"
    > GUID="2057ad4f-8511-4ec6-b7be-c9652571e407">
    > <FiRstName>Rob2</FiRstName>
    > <LAsTNaMe>Smith2</LAsTNaMe>
    > <thePassword>SecretSmith2</thePassword>
    > <theEmaiL></theEmaiL>
    > <Age>18</Age>
    > <UserId>Rob2Smith</UserId>
    > </MyEmployee>
    > - <MyEmployee xmlns:mytest="http://www.w3.org/2001/XMLSchemaMyOwn"
    > GUID="325e0a07-329d-4544-ba36-e79abe2cbc6b">
    > <FiRstName>Rob3</FiRstName>
    > <LAsTNaMe>Smith3</LAsTNaMe>
    > <thePassword>SecretSmith3</thePassword>
    > <theEmaiL></theEmaiL>
    > <Age>33</Age>
    > <UserId>Rob3Smith</UserId>
    > </MyEmployee>
    > </ARootElement>
    >
    > //Here is the relevant code for deserializing the above. It does not
    > work, since the condition xr.Name == “DecoratedPerson” is never
    > reached.


    The element name in the XML document is "MyEmployee", not
    "DecoratedPerson" so you need to check for "MyEmployee".


    --

    Martin Honnen
    http://msmvps.com/blogs/martin_honnen/
     
    Martin Honnen, Jul 23, 2009
    #11
  12. RayLopez99

    RayLopez99 Guest

    Re: Append to a file using XML Serialization? Easy way to do this?

    On Jul 23, 10:13 am, Martin Honnen <> wrote:

    > The element name in the XML document is "MyEmployee", not
    > "DecoratedPerson" so you need to check for "MyEmployee".
    >



    Thanks again, and I am getting closer, but the problem now (that is
    fatal I'm afraid, unless I can figure this out with your help) is that
    only odd numbered elements are being deserialized, as can be seen from
    the output below. The other, "longer" way of doing it is working for
    all elements.

    Any ideas?

    RL

    //output from the "finally" statement
    //only odd numbered elements are being stored--why? Even numbered
    elements being skipped over
    count is: 4
    these values exist for DecoratedPerson!:
    Smith1,Rob1,SecretSmith,,19,Rob1Smith,1e1e6ac3-b000-4eef-
    a755-43417cdb4089
    these values exist for DecoratedPerson!:
    Smith3,Rob3,SecretSmith3,,33,Rob3Smith,
    1faa61e4-8449-47c1-8726-b8a611ce25b1
    these values exist for DecoratedPerson!:
    Smith5,Rob5,SecretSmith5,,55,Rob6Smith,
    6a36aa81-058b-4bee-bdb7-a25f4afe6061
    these values exist for DecoratedPerson!:
    Smith7,Rob7,SecretSmith7,,77,Rob7Smith,b681b7aa-
    f79a-4e36-be5a-6776024e8d25




    //the xml file

    <?xml version="1.0" encoding="utf-8" ?>
    - <ARootElement>
    - <MyEmployee xmlns:mytest="http://www.w3.org/2001/XMLSchemaMyOwn"
    GUID="1e1e6ac3-b000-4eef-a755-43417cdb4089">
    <FiRstName>Rob1</FiRstName>
    <LAsTNaMe>Smith1</LAsTNaMe>
    <thePassword>SecretSmith</thePassword>
    <theEmaiL></theEmaiL>
    <Age>19</Age>
    <UserId>Rob1Smith</UserId>
    </MyEmployee>
    - <MyEmployee xmlns:mytest="http://www.w3.org/2001/XMLSchemaMyOwn"
    GUID="f6f908ed-64e8-4639-b0bc-7db529a1dc78">
    <FiRstName>Rob2</FiRstName>
    <LAsTNaMe>Smith2</LAsTNaMe>
    <thePassword>SecretSmith2</thePassword>
    <theEmaiL></theEmaiL>
    <Age>18</Age>
    <UserId>Rob2Smith</UserId>
    </MyEmployee>
    - <MyEmployee xmlns:mytest="http://www.w3.org/2001/XMLSchemaMyOwn"
    GUID="1faa61e4-8449-47c1-8726-b8a611ce25b1">
    <FiRstName>Rob3</FiRstName>
    <LAsTNaMe>Smith3</LAsTNaMe>
    <thePassword>SecretSmith3</thePassword>
    <theEmaiL></theEmaiL>
    <Age>33</Age>
    <UserId>Rob3Smith</UserId>
    </MyEmployee>
    - <MyEmployee xmlns:mytest="http://www.w3.org/2001/XMLSchemaMyOwn"
    GUID="d52684ac-2392-41d5-bad3-6316f9d9fbb2">
    <FiRstName>Rob4</FiRstName>
    <LAsTNaMe>Smith4</LAsTNaMe>
    <thePassword>SecretSmith4</thePassword>
    <theEmaiL></theEmaiL>
    <Age>44</Age>
    <UserId>Rob4Smith</UserId>
    </MyEmployee>
    - <MyEmployee xmlns:mytest="http://www.w3.org/2001/XMLSchemaMyOwn"
    GUID="6a36aa81-058b-4bee-bdb7-a25f4afe6061">
    <FiRstName>Rob5</FiRstName>
    <LAsTNaMe>Smith5</LAsTNaMe>
    <thePassword>SecretSmith5</thePassword>
    <theEmaiL></theEmaiL>
    <Age>55</Age>
    <UserId>Rob6Smith</UserId>
    </MyEmployee>
    - <MyEmployee xmlns:mytest="http://www.w3.org/2001/XMLSchemaMyOwn"
    GUID="95aee4ce-b8b6-4e01-83da-9e5072370e28">
    <FiRstName>Rob6</FiRstName>
    <LAsTNaMe>Smith6</LAsTNaMe>
    <thePassword>SecretSmith5</thePassword>
    <theEmaiL></theEmaiL>
    <Age>66</Age>
    <UserId>Rob6Smith</UserId>
    </MyEmployee>
    - <MyEmployee xmlns:mytest="http://www.w3.org/2001/XMLSchemaMyOwn"
    GUID="b681b7aa-f79a-4e36-be5a-6776024e8d25">
    <FiRstName>Rob7</FiRstName>
    <LAsTNaMe>Smith7</LAsTNaMe>
    <thePassword>SecretSmith7</thePassword>
    <theEmaiL></theEmaiL>
    <Age>77</Age>
    <UserId>Rob7Smith</UserId>
    </MyEmployee>
    </ARootElement>
     
    RayLopez99, Jul 23, 2009
    #12
  13. Re: Append to a file using XML Serialization? Easy way to do this?

    RayLopez99 wrote:
    > On Jul 23, 10:13 am, Martin Honnen <> wrote:
    >
    >> The element name in the XML document is "MyEmployee", not
    >> "DecoratedPerson" so you need to check for "MyEmployee".
    >>

    >
    >
    > Thanks again, and I am getting closer, but the problem now (that is
    > fatal I'm afraid, unless I can figure this out with your help) is that
    > only odd numbered elements are being deserialized, as can be seen from
    > the output below. The other, "longer" way of doing it is working for
    > all elements.


    Can you post that class you are deserializing to?

    --

    Martin Honnen
    http://msmvps.com/blogs/martin_honnen/
     
    Martin Honnen, Jul 23, 2009
    #13
  14. RayLopez99

    RayLopez99 Guest

    Re: Append to a file using XML Serialization? Easy way to do this?

    On Jul 23, 12:56 pm, Martin Honnen <> wrote:
    > RayLopez99 wrote:
    > > On Jul 23, 10:13 am, Martin Honnen <> wrote:

    >
    > >> The element name in the XML document is "MyEmployee", not
    > >> "DecoratedPerson" so you need to check for "MyEmployee".

    >
    > > Thanks again, and I am getting closer, but the problem now (that is
    > > fatal I'm afraid, unless I can figure this out with your help) is that
    > > only odd numbered elements are being deserialized, as can be seen from
    > > the output below.  The other, "longer" way of doing it is working for
    > > all elements.

    >
    > Can you post that class you are deserializing to?
    >
    >


    Here it is--below.

    Like I said the "long" or "slow" way works fine. I would like to use
    or learn this 'quicker' / non-case/switch form of deserialization if
    possible however.

    RL

    [XmlRoot(ElementName="MyEmployee")]
    public class DecoratedPerson
    {
    private string firstName;
    private string lastName;
    private string password;
    private string email;
    private int age;
    private Guid userGuid;
    private string userId;

    [XmlElement(ElementName="FiRstName")]
    public string FirstName
    {
    get
    {
    return firstName;

    }
    set
    {
    firstName = value;
    }
    }

    [XmlElement(ElementName="LAsTNaMe")]
    public string LastName
    {
    get
    {
    return lastName;

    }
    set
    {
    lastName = value;
    }
    }

    [XmlElement(ElementName = "thePassword")]
    public string Password
    {
    get
    {
    return password;

    }
    set
    {
    password = value;
    }
    }

    [XmlElement(ElementName = "theEmaiL")]
    public string Email
    {
    get
    {
    return email;

    }
    set
    {
    email = value;
    }
    }

    [XmlElement(IsNullable=false)]
    public int Age
    {
    get
    {
    return age;

    }
    set
    {
    age = value;
    }
    }

    [XmlAttribute(AttributeName="GUID")]
    public Guid UserGuid
    {
    get
    {
    return userGuid;

    }
    set
    {
    userGuid = value;
    }
    }

    [XmlElement(IsNullable = true)]
    public string UserId
    {
    get
    {
    return userId;

    }
    set
    {
    userId = value;
    }
    }


    public DecoratedPerson()
    {

    firstName = String.Empty;
    lastName = String.Empty;
    password = String.Empty;
    email = String.Empty;
    age = -1;
    userGuid = new Guid();
    userId = String.Empty;


    }
    }
     
    RayLopez99, Jul 23, 2009
    #14
  15. Re: Append to a file using XML Serialization? Easy way to do this?

    RayLopez99 wrote:

    > Like I said the "long" or "slow" way works fine. I would like to use
    > or learn this 'quicker' / non-case/switch form of deserialization if
    > possible however.


    I can't reproduce the problem with the code I suggested earlier. With
    the XML being

    <ARootElement>
    <MyEmployee xmlns:mytest="http://www.w3.org/2001/XMLSchemaMyOwn"
    GUID="1e1e6ac3-b000-4eef-a755-43417cdb4089">
    <FiRstName>Rob1</FiRstName>
    <LAsTNaMe>Smith1</LAsTNaMe>
    <thePassword>SecretSmith</thePassword>
    <theEmaiL></theEmaiL>
    <Age>19</Age>
    <UserId>Rob1Smith</UserId>
    </MyEmployee>
    <MyEmployee xmlns:mytest="http://www.w3.org/2001/XMLSchemaMyOwn"
    GUID="f6f908ed-64e8-4639-b0bc-7db529a1dc78">
    <FiRstName>Rob2</FiRstName>
    <LAsTNaMe>Smith2</LAsTNaMe>
    <thePassword>SecretSmith2</thePassword>
    <theEmaiL></theEmaiL>
    <Age>18</Age>
    <UserId>Rob2Smith</UserId>
    </MyEmployee>
    <MyEmployee xmlns:mytest="http://www.w3.org/2001/XMLSchemaMyOwn"
    GUID="1faa61e4-8449-47c1-8726-b8a611ce25b1">
    <FiRstName>Rob3</FiRstName>
    <LAsTNaMe>Smith3</LAsTNaMe>
    <thePassword>SecretSmith3</thePassword>
    <theEmaiL></theEmaiL>
    <Age>33</Age>
    <UserId>Rob3Smith</UserId>
    </MyEmployee>
    <MyEmployee xmlns:mytest="http://www.w3.org/2001/XMLSchemaMyOwn"
    GUID="d52684ac-2392-41d5-bad3-6316f9d9fbb2">
    <FiRstName>Rob4</FiRstName>
    <LAsTNaMe>Smith4</LAsTNaMe>
    <thePassword>SecretSmith4</thePassword>
    <theEmaiL></theEmaiL>
    <Age>44</Age>
    <UserId>Rob4Smith</UserId>
    </MyEmployee>
    <MyEmployee xmlns:mytest="http://www.w3.org/2001/XMLSchemaMyOwn"
    GUID="6a36aa81-058b-4bee-bdb7-a25f4afe6061">
    <FiRstName>Rob5</FiRstName>
    <LAsTNaMe>Smith5</LAsTNaMe>
    <thePassword>SecretSmith5</thePassword>
    <theEmaiL></theEmaiL>
    <Age>55</Age>
    <UserId>Rob6Smith</UserId>
    </MyEmployee>
    <MyEmployee xmlns:mytest="http://www.w3.org/2001/XMLSchemaMyOwn"
    GUID="95aee4ce-b8b6-4e01-83da-9e5072370e28">
    <FiRstName>Rob6</FiRstName>
    <LAsTNaMe>Smith6</LAsTNaMe>
    <thePassword>SecretSmith5</thePassword>
    <theEmaiL></theEmaiL>
    <Age>66</Age>
    <UserId>Rob6Smith</UserId>
    </MyEmployee>
    <MyEmployee xmlns:mytest="http://www.w3.org/2001/XMLSchemaMyOwn"
    GUID="b681b7aa-f79a-4e36-be5a-6776024e8d25">
    <FiRstName>Rob7</FiRstName>
    <LAsTNaMe>Smith7</LAsTNaMe>
    <thePassword>SecretSmith7</thePassword>
    <theEmaiL></theEmaiL>
    <Age>77</Age>
    <UserId>Rob7Smith</UserId>
    </MyEmployee>
    </ARootElement>

    this code

    List<DecoratedPerson> persons = new List<DecoratedPerson>();
    XmlSerializer ser = new XmlSerializer(typeof(DecoratedPerson));
    using (XmlReader reader =
    XmlReader.Create(@"..\..\XMLFile1.xml"))
    {
    while (reader.Read())
    {
    if (reader.NodeType == XmlNodeType.Element &&
    reader.LocalName == "MyEmployee")
    {
    DecoratedPerson p =
    (DecoratedPerson)ser.Deserialize(reader);
    persons.Add(p);
    }
    }
    reader.Close();
    }
    Console.WriteLine("Found {0} items:", persons.Count);
    foreach (DecoratedPerson p in persons)
    {
    Console.WriteLine(p.FirstName);
    }

    finds all seven elements and outputs (.NET 3.5 SP 1):

    Found 7 items:
    Rob1
    Rob2
    Rob3
    Rob4
    Rob5
    Rob6
    Rob7

    I am not sure what you are doing differently but somehow your code must
    be different that it skips every even item.

    --

    Martin Honnen
    http://msmvps.com/blogs/martin_honnen/
     
    Martin Honnen, Jul 24, 2009
    #15
  16. RayLopez99

    RayLopez99 Guest

    Re: Append to a file using XML Serialization? Easy way to do this?

    On Jul 24, 7:05 am, Martin Honnen <> wrote:

    >
    > I am not sure what you are doing differently but somehow your code must
    > be different that it skips every even item.
    >



    Yes, it was bizarre. Unfortunately I cannot add your "short" way to
    my library since it doesn't work for ASP.web type design (C# code
    behind). I will continue doing it the "long" way, which does work.

    The only thing I could think of, is that sometimes Web (ASP) stuff
    needs state variables, and you have to store them, though why the
    even /odd nodes would be not saved is beyond me; perhaps after adding
    every node there is a page refresh and some information is lost. But
    I have no idea why this would be (but with ASP it just happens that
    way it seems) and the debugger is no help. If this was a commercial
    project I would try a different data structure and rebuild from
    scratch, or perhaps just use the "long" way, but as this was an
    exercise I'm moving on.

    Frankly, I find XML coding a bit too complex. I even have the book by
    Bipin Joshi (APress) on XML and it doesn't help much. But in those
    instances I have to use XML I guess I can, with some effort.

    Thanks for your help.

    RL
     
    RayLopez99, Jul 25, 2009
    #16
  17. RayLopez99

    RayLopez99 Guest

    Re: Append to a file using XML Serialization? Easy way to do this?

    On Jul 24, 7:05 am, Martin Honnen <> wrote:
    > I am not sure what you are doing differently but somehow your code must
    > be different that it skips every even item.
    >


    Today, just for fun, I tried similar code in C# Forms rather than C#
    ASP.NET but it again skips every other node (even nodes), just like in
    ASP.NET. Thus only first names Rob1 and Rob3 are being read back from
    the XML file, but not Rob2. Strange how only Rob2 shows up in
    Debug.Writeline, see below.

    Too bad, as this "short way" would have been nice. Strange but in
    console mode I don't have any problems. One possible problem: perhaps
    in C# when </MyEmployee> is encountered, somehow the node skips? But
    why not this problem in Console mode?

    BTW, do...while does not seem to affect things differently (rather
    than just while) nor does .localname vs .name

    RL

    private void button1_Click(object sender, EventArgs e)
    {
    DecoratedPerson myDecPerson1 = new DecoratedPerson();
    myDecPerson1.FirstName = "Rob1";
    myDecPerson1.LastName = "Smith1";
    myDecPerson1.Password = "SecretSmith";
    myDecPerson1.Email = "";
    myDecPerson1.Age = int.Parse("19");
    myDecPerson1.UserId = "Rob1Smith";
    Guid myGuid = new Guid();
    myGuid = System.Guid.NewGuid();
    myDecPerson1.UserGuid = myGuid;
    // add to List
    myDecPersonList.Add(myDecPerson1);

    //NOTE: http://groups.google.com/group/comp.text.xml/browse_thread/thread/41bc4904526329da?hl=en#


    DecoratedPerson myDecPerson2 = new DecoratedPerson();

    myDecPerson2.FirstName = "Rob2T";
    myDecPerson2.LastName = "Smith2T";
    myDecPerson2.Password = "SecretSmith2T";
    myDecPerson2.Email = "";
    myDecPerson2.Age = int.Parse("188");
    myDecPerson2.UserId = "Rob2TSmith";
    myGuid = new Guid();
    myGuid = System.Guid.NewGuid();
    myDecPerson2.UserGuid = myGuid;
    myDecPersonList.Add(myDecPerson2);

    DecoratedPerson myDecPerson3 = new DecoratedPerson();

    myDecPerson3.FirstName = "Rob3";
    myDecPerson3.LastName = "Smith3";
    myDecPerson3.Password = "SecretSmith3";
    myDecPerson3.Email = "";
    myDecPerson3.Age = int.Parse("333");
    myDecPerson3.UserId = "Rob3Smith";
    myGuid = new Guid();
    myGuid = System.Guid.NewGuid();
    myDecPerson3.UserGuid = myGuid;
    myDecPersonList.Add(myDecPerson3);


    string totalFilepath = System.IO.Path.GetDirectoryName
    (System.Reflection.Assembly.GetExecutingAssembly().Location);
    totalFilepath += @"\MyXMLfile.xml"; //add the name of the
    file
    Debug.WriteLine("Thsi is the path: " + totalFilepath);
    XmlSerializerNamespaces ns = new XmlSerializerNamespaces
    ();
    //ns.Add("", "");
    ns.Add("mytest", "http://www.w3.org/2001/XMLSchemaMyOwn");

    XmlWriterSettings settings = new XmlWriterSettings();
    settings.OmitXmlDeclaration = false; // Remove the <?xml
    version="1.0" encoding="utf-8"?>


    XmlWriter writer = XmlWriter.Create(totalFilepath,
    settings); //create used: // culver NOTE TO DO: if you wanted to add
    to the end of an existing XML file you would have to read the file
    first into memory...

    writer.WriteStartElement("ARootElement");

    // FileStream stream = new FileStream(totalFilepath,
    FileMode.Create);
    XmlSerializer serializer = new XmlSerializer(typeof
    (DecoratedPerson));


    foreach (DecoratedPerson p in myDecPersonList)
    {

    serializer.Serialize(writer, p, ns);
    }

    writer.WriteEndElement(); //writes </ARootElement>
    automatically

    writer.Close();
    //stream.Close();



    }

    private void button2_Click(object sender, EventArgs e)
    {

    ////deserialize

    List<DecoratedPerson> persons = new List<DecoratedPerson>
    ();

    XmlSerializer ser = new XmlSerializer(typeof
    (DecoratedPerson));

    string totalFilepath = System.IO.Path.GetDirectoryName
    (System.Reflection.Assembly.GetExecutingAssembly().Location);
    totalFilepath += @"\MyXMLfile.xml"; //add the name of the
    file



    try
    {

    using (XmlReader reader = XmlReader.Create
    (totalFilepath))
    {
    DecoratedPerson p;

    do
    {
    Debug.WriteLine("reader is: " + reader.Name +
    "," + reader.NodeType.ToString() + "," + reader.LocalName + "," +
    reader.ValueType.ToString() + "," + reader.Value.ToString());


    if (reader.NodeType == XmlNodeType.Element &&
    reader.Name == "MyEmployee")
    {
    p = (DecoratedPerson)ser.Deserialize
    (reader);
    persons.Add(p);
    }
    }
    while (reader.Read());

    reader.Close();
    }
    }
    catch (FileNotFoundException fNF)
    {
    Debug.WriteLine(fNF.Message);

    }
    catch (Exception ex)
    {
    Debug.WriteLine(ex.Message);

    }

    Console.WriteLine("Found {0} items:", persons.Count);
    foreach (DecoratedPerson p in persons)
    {
    Debug.WriteLine(p.FirstName);
    }


    }




    //
    reader is: xml,XmlDeclaration,xml,System.String,version="1.0"
    encoding="utf-8"
    reader is: ARootElement,Element,ARootElement,System.String,
    reader is: MyEmployee,Element,MyEmployee,System.String,
    reader is: FiRstName,Element,FiRstName,System.String,
    reader is: ,Text,,System.String,Rob2T
    reader is: FiRstName,EndElement,FiRstName,System.String,
    reader is: LAsTNaMe,Element,LAsTNaMe,System.String,
    reader is: ,Text,,System.String,Smith2T
    reader is: LAsTNaMe,EndElement,LAsTNaMe,System.String,
    reader is: thePassword,Element,thePassword,System.String,
    reader is: ,Text,,System.String,SecretSmith2T
    reader is: thePassword,EndElement,thePassword,System.String,
    reader is: theEmaiL,Element,theEmaiL,System.String,
    reader is: ,Text,,System.String,
    reader is: theEmaiL,EndElement,theEmaiL,System.String,
    reader is: Age,Element,Age,System.String,
    reader is: ,Text,,System.String,188
    reader is: Age,EndElement,Age,System.String,
    reader is: UserId,Element,UserId,System.String,
    reader is: ,Text,,System.String,Rob2TSmith
    reader is: UserId,EndElement,UserId,System.String,
    reader is: MyEmployee,EndElement,MyEmployee,System.String,
    reader is: MyEmployee,Element,MyEmployee,System.String,

    // only nodes 1, 3 are read back! Not node 2
    Rob1
    Rob3

    // XML file (which is correctly written) here:

    <?xml version="1.0" encoding="utf-8" ?>
    - <ARootElement>
    - <MyEmployee xmlns:mytest="http://www.w3.org/2001/XMLSchemaMyOwn"
    GUID="84b9a753-8106-4870-a7a3-6814a0742bf5">
    <FiRstName>Rob1</FiRstName>
    <LAsTNaMe>Smith1</LAsTNaMe>
    <thePassword>SecretSmith</thePassword>
    <theEmaiL></theEmaiL>
    <Age>19</Age>
    <UserId>Rob1Smith</UserId>
    </MyEmployee>
    - <MyEmployee xmlns:mytest="http://www.w3.org/2001/XMLSchemaMyOwn"
    GUID="2d05ddc3-ff2e-45f5-b350-a37bd6d6bb95">
    <FiRstName>Rob2T</FiRstName>
    <LAsTNaMe>Smith2T</LAsTNaMe>
    <thePassword>SecretSmith2T</thePassword>
    <theEmaiL></theEmaiL>
    <Age>188</Age>
    <UserId>Rob2TSmith</UserId>
    </MyEmployee>
    - <MyEmployee xmlns:mytest="http://www.w3.org/2001/XMLSchemaMyOwn"
    GUID="d679e964-08fe-45fa-8264-42fa9e9e3307">
    <FiRstName>Rob3</FiRstName>
    <LAsTNaMe>Smith3</LAsTNaMe>
    <thePassword>SecretSmith3</thePassword>
    <theEmaiL></theEmaiL>
    <Age>333</Age>
    <UserId>Rob3Smith</UserId>
    </MyEmployee>
    </ARootElement>

    // decorated class here:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Xml.Serialization;

    namespace XmlForms
    {
    [XmlRoot(ElementName = "MyEmployee")]

    public class DecoratedPerson
    {

    private string firstName;
    private string lastName;
    private string password;
    private string email;
    private int age;
    private Guid userGuid;
    private string userId;

    [XmlElement(ElementName = "FiRstName")]
    public string FirstName
    {
    get
    {
    return firstName;

    }
    set
    {
    firstName = value;
    }
    }

    [XmlElement(ElementName = "LAsTNaMe")]
    public string LastName
    {
    get
    {
    return lastName;

    }
    set
    {
    lastName = value;
    }
    }

    [XmlElement(ElementName = "thePassword")]
    public string Password
    {
    get
    {
    return password;

    }
    set
    {
    password = value;
    }
    }

    [XmlElement(ElementName = "theEmaiL")]
    public string Email
    {
    get
    {
    return email;

    }
    set
    {
    email = value;
    }
    }

    [XmlElement(IsNullable = false)]
    public int Age
    {
    get
    {
    return age;

    }
    set
    {
    age = value;
    }
    }

    [XmlAttribute(AttributeName = "GUID")]
    public Guid UserGuid
    {
    get
    {
    return userGuid;

    }
    set
    {
    userGuid = value;
    }
    }

    [XmlElement(IsNullable = true)]
    public string UserId
    {
    get
    {
    return userId;

    }
    set
    {
    userId = value;
    }
    }


    public DecoratedPerson()
    {

    firstName = String.Empty;
    lastName = String.Empty;
    password = String.Empty;
    email = String.Empty;
    age = -1;
    userGuid = new Guid();
    userId = String.Empty;


    }
    }
    }
     
    RayLopez99, Aug 4, 2009
    #17
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Replies:
    3
    Views:
    1,087
  2. Dimitri Ognibene
    Replies:
    4
    Views:
    824
    Dimitri Ognibene
    Sep 2, 2006
  3. HALLES
    Replies:
    5
    Views:
    348
    HALLES
    May 31, 2005
  4. HYRY
    Replies:
    10
    Views:
    647
    Bruno Desthuilliers
    Sep 26, 2007
  5. Ramunas Urbonas
    Replies:
    1
    Views:
    427
    Dino Chiesa [Microsoft]
    Jul 27, 2004
Loading...

Share This Page