How to Create an Xml Document Using Xmldocument

How to create XML in C#

//Create XmlDocument
XmlDocument xmlDoc = new XmlDocument();

//Create the root element
XmlNode outputsElement = xmlDoc.CreateElement("outputs");

//Create the child element
XmlElement Element = xmlDoc.CreateElement("output");

//Create "name" Attribute
XmlAttribute nameAtt = xmlDoc.CreateAttribute("name");
Element.Attributes.Append(nameAtt);

//Create "value" Attribute
XmlAttribute valueAtt = xmlDoc.CreateAttribute("value");
Element.Attributes.Append(valueAtt);

//Create "type" Attribute
XmlAttribute typeAtt = xmlDoc.CreateAttribute("type");
Element.Attributes.Append(typeAtt);

//Append child element into root element
outputsElement.AppendChild(Element);

and to return it as string:
xmlDoc.OuterXml;

create nested xml document in c#

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);

Create XML file using c# like below format

You can create your required XML using the XML Document Object Model as follows:

var soapNs = @"http://schemas.xmlsoap.org/soap/envelope/";
var bodyNs = @"";

var doc = new XmlDocument();
var root = doc.AppendChild(doc.CreateElement("SOAP-ENV", "Envelope", soapNs));
var body = root.AppendChild(doc.CreateElement("SOAP-ENV", "Body", soapNs));

body.AppendChild(doc.CreateElement("", "AddressLine1", bodyNs)).InnerText = "50 W TOWN ST";
body.AppendChild(doc.CreateElement("", "AddressLine2", bodyNs)).InnerText = "STE 400";
body.AppendChild(doc.CreateElement("", "City", bodyNs)).InnerText = "COLUMBUS";
body.AppendChild(doc.CreateElement("", "State", bodyNs)).InnerText = "OH";
body.AppendChild(doc.CreateElement("", "Zip", bodyNs)).InnerText = "43215";
body.AppendChild(doc.CreateElement("", "Zip4", bodyNs)).InnerText = "";

Using this approach, the following XML is generated:

<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
<SOAP-ENV:Body>
<AddressLine1>50 W TOWN ST</AddressLine1>
<AddressLine2>STE 400</AddressLine2>
<City>COLUMBUS</City>
<State>OH</State>
<Zip>43215</Zip>
<Zip4></Zip4>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>

Notes:

  1. A well-formed XML document must have one and only one root element. In the initial version of your question, you try to add multiple nodes directly to the XmlDocument doc:

    doc.AppendChild(docNode);
    // Snip some code
    doc.AppendChild(AddressRequestNode);

    Attempting to do this causes the This document already has a 'DocumentElement' node. exception to be thrown.

  2. Your XML document has elements in two namespaces: http://schemas.xmlsoap.org/soap/envelope/ and the empty namespace. In situations such as this, it's easiest to use the XmlDocument.CreateElement(string prefix, string localName, string namespaceURI) API and always explicitly specify the namespace URI, rather than simply specifying the namespace lookup prefix and hoping you had correctly initialized the corresponding xmlns: prefix value earlier.

    In the sample XML, the Envelope and Body nodes are in the http://schemas.xmlsoap.org/soap/envelope/ namespace while their child nodes are in the empty namespace, which is what is reflected in my sample code.

  3. XmlNode.AppendChild(XmlNode) returns the appended child and so can be used in a fluent style.

  4. In the sample XML the innermost elements are explicitly specified to have a default namespace of "":

    <AddressLine1 xmlns="">50 W TOWN ST</AddressLine1>

    Actually the xmlns="" is unnecessary because there is no default namespace specified at a higher level in the XML. Thus the following is semantically identical and sufficient:

    <AddressLine1>50 W TOWN ST</AddressLine1>

    If for some reason you are required to have this redundant namespace declaration, you can do:

    var line1 = body.AppendChild(doc.CreateElement("", "AddressLine1", bodyNs));
    line1.Attributes.Append(doc.CreateAttribute("xmlns")).Value = bodyNs;
    line1.InnerText = "50 W TOWN ST";

    Which results in

    <AddressLine1 xmlns="">50 W TOWN ST</AddressLine1>
  5. XmlElement.InnerText can be used to set the text value of a element with no child elements. This is more succinct than calling CreateTextNode() then appending the result to the DOM.

Working sample .Net fiddle here.

XML file creation using XDocument in C#

LINQ to XML allows this to be much simpler, through three features:

  • You can construct an object without knowing the document it's part of
  • You can construct an object and provide the children as arguments
  • If an argument is iterable, it will be iterated over

So here you can just do:

void Main()
{
List<string> list = new List<string>
{
"Data1", "Data2", "Data3"
};

XDocument doc =
new XDocument(
new XElement("file",
new XElement("name", new XAttribute("filename", "sample")),
new XElement("date", new XAttribute("modified", DateTime.Now)),
new XElement("info",
list.Select(x => new XElement("data", new XAttribute("value", x)))
)
)
);

doc.Save("Sample.xml");
}

I've used this code layout deliberately to make the code itself reflect the structure of the document.

If you want an element that contains a text node, you can construct that just by passing in the text as another constructor argument:

// Constructs <element>text within element</element>
XElement element = new XElement("element", "text within element");

Create file and write xml there (C#)

Since you're writing Windows 10 universal app, XmlDocument.Save(string) is unavailable. Instead, use

    using (FileStream fs = new FileStream("test.xml", FileMode.Create))
{
doc.Save(fs);
}

How to get XML with header (?xml version=1.0...)?

Create an XML-declaration using XmlDocument.CreateXmlDeclaration Method:

XmlNode docNode = xml.CreateXmlDeclaration("1.0", "UTF-8", null);
xml.AppendChild(docNode);

Note: please take a look at the documentation for the method, especially for encoding parameter: there are special requirements for values of this parameter.



Related Topics



Leave a reply



Submit