Link to home
Start Free TrialLog in
Avatar of RHopkinson
RHopkinson

asked on

C# + XML writing

I'm trying a little self study and i'm having a problem with the following. Any code help or if you know a resource that can explain how to properly write the code would be amazing.

Here is the output i'm looking for in my XML file:

<?xml version="1.0" ?>
<Document>
     <Pair>
          <Name>somevalue</Name>
          <Value>somevalue</Value>
     </Pair>
     <Pair>
          <Name>somevalue</Name>
          <Value>somevalue</Value>
     </Pair>
</Document>

Here is my code:

public void saveXML()
            {
                  XmlDocument xmldoc;
                  XmlNode xmlnode;
                  XmlElement xmlelem;
                  XmlElement xmlelem2;
                  XmlText xmltext;

                  xmldoc=new XmlDocument();
                  //let's add the XML declaration section
                  xmlnode=xmldoc.CreateNode(XmlNodeType.XmlDeclaration,"","");
                  xmldoc.AppendChild(xmlnode);
                  
                  //let's add the root element
                  xmlelem=xmldoc.CreateElement("","Document","");
                  xmldoc.AppendChild(xmlelem);

                  for(int i=0; i < 3;i++)
                  {
                        //add a pair
                        xmlelem=xmldoc.CreateElement("","Pair","");         // <<--Recieve error here
                        xmldoc.AppendChild(xmlelem);                             //

                        //let's add another element (child of the Pair)
                        xmlelem = xmldoc.CreateElement("","Name","");
                        xmltext =xmldoc.CreateTextNode( "somevalue");
                        xmlelem.AppendChild(xmltext);
                        xmldoc.ChildNodes.Item(1).AppendChild(xmlelem);

                        xmlelem2 = xmldoc.CreateElement("","Value","");
                        xmltext =xmldoc.CreateTextNode( "somevalue" );
                        xmlelem2.AppendChild(xmltext);
                        xmldoc.ChildNodes.Item(1).AppendChild(xmlelem2);
                  }
                  //save the XML document in a file: C:\namevalue.xml
                  xmldoc.Save("c:\\namevalue.xml");
            }

Thanks for your time!
ASKER CERTIFIED SOLUTION
Avatar of Ravi Singh
Ravi Singh
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of RHopkinson
RHopkinson

ASKER

Thanks for the quick reply and excellent code! very easy to understand!