Link to home
Start Free TrialLog in
Avatar of intikhabk
intikhabk

asked on

Create XML in C#

How do I create the below XML example using XDocument class in C#

Is there any better approach other than XDocument

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<Data>
  <Books>
    <Book key="key1" value="value1" />
    <Book key="key2" value="value2" />
  </Books>
  <CDS>
    <CD>
      <Key>key1</Key>
      <Value>value1</Value>
    </CD>
    <CD>
      <Key>key2</Key>
      <Value>value2</Value>
    </CD>
  </CDS>
</Data>

Avatar of silemone
silemone
Flag of United States of America image

XDocument works well...better approach?  if you're using d database then return data from dataBase as xml
good example on how to build document

http://www.example-code.com/csharp/csCreateXml.asp
this is the other option that you wanted...use the framework and build your xml like that...
Avatar of Daniel Reynolds
The following bit of code might help if you are trying to do it all programmatically. It will give you an idea of how to traverse and build it from the ground up.

            XmlDataDocument oXMLDoc = new XmlDataDocument();
            XmlNode oRootNode;
            XmlNode oXMLNode;
             XmlNode oNode1;
            XmlNode oNode2;
            XmlAttribute oXMLAttribute;

               oXMLDoc.AppendChild(oXMLDoc.CreateProcessingInstruction("xml", "version=\"1.0\" encoding=\"utf-8\""));
                oRootNode = oXMLDoc.CreateElement("Data");
                oNode1 = oXMLDoc.CreateElement("Books");
                oRootNode.AppendChild(oXMLNode);
                oNode2 = oXMLDoc.CreateElement("Book");
                oXMLAttribute = oXMLDoc.CreateAttribute("key");
                oXMLAttribute.Value = "key1";
                oNode2.Attributes.Append(oXMLAttribute);
                oXMLAttribute = oXMLDoc.CreateAttribute("value");
                oXMLAttribute.Value = "Value1";
                oNode2.Attributes.Append(oXMLAttribute);

                oNode1.AppendChild(oNode2);

                oXMLDoc.Save("filename.xml");
that would be using System.Xml
ASKER CERTIFIED SOLUTION
Avatar of adathelad
adathelad
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