Search code examples
c#xmlxmldocument

create nested xml document in c#


i am a newbie in XmlDocument.i want to create nested xml document in c#.through some reaserach i fount that XmlDocument are recommended way to create xml if size is small.

i am having some trouble while creating nested tags

code:

XmlDocument doc = new XmlDocument();
XmlDeclaration xDeclare = doc.CreateXmlDeclaration("1.0", "UTF-8", null);
XmlElement root = doc.DocumentElement;
doc.InsertBefore(xDeclare, root);
XmlElement el = (XmlElement)doc.AppendChild(doc.CreateElement("FIXML"));
el.AppendChild(doc.CreateElement("Header")).InnerText = "";
el.AppendChild(doc.CreateElement("RequestHeader")).InnerText = "";
el.AppendChild(doc.CreateElement("MessageKey")).InnerText = "";
el.AppendChild(doc.CreateElement("RequestUUID")).InnerText = "938692349";
Console.WriteLine(doc.OuterXml);

its giving output as

<?xml version="1.0" encoding="UTF-8"?>
<FIXML>
    <Header></Header>
    <RequestHeader></RequestHeader>
    <MessageKey></MessageKey>
    <RequestUUID>938692349</RequestUUID>
</FIXML>

but it should be like

<?xml version="1.0" encoding="UTF-8"?>
<FIXML>
    <Header>
        <RequestHeader>
            <MessageKey>
                <RequestUUID>938692349</RequestUUID>
            </MessageKey>
        </RequestHeader>
    </Header>
</FIXML>

Solution

  • Much easier with the newer XML API (XDocument)

    var doc = 
        new XElement("FIXML",        // you can optionally add an XDocument as outer element
          new XElement ("Header", 
              .... // more child elements, values and/or attributes
              new XElement("RequestUUID", 938692349)
          ));
    
    
    doc.Save(fileName);