%% Use Document Fragment to Create Content Based on Run-Time Data
% Suppose that your application creates chapters and that the number of chapters is determined at run time. You can write a function, such as the createChapters  function, defined at the end of this example, to create a specified number of chapter elements and return them as a document fragment.
% Create a document that has a root element named book.

import matlab.io.xml.dom.*

doc = Document("book");
docElemRoot = getDocumentElement(doc);

% Call the function createChapters to return three chapters as a matlab.io.xml.dom.DocumentFragment object. Append the fragment to the document.

docFrag = createChapters(doc,3);
appendChild(docElemRoot,docFrag);

% Write the document to the file book.xml.

xmlFileName = "book.xml";
writer = matlab.io.xml.dom.DOMWriter;
writeToFile(writer,doc,xmlFileName);

% Display the resulting XML.

type(xmlFileName);

%
%% The createChapters Function
% The function createChapters returns a DocumentFragment object that contains the specified number of chapter elements.

function docFrag = createChapters(doc,n)
docFrag = createDocumentFragment(doc);
for i=1:n
    chapter = createElement(doc,"chapter");
    appendChild(chapter,createTextNode(doc,sprintf("Chapter %d",i)));
    appendChild(docFrag,chapter);
end
end

% Copyright 2020 The MathWorks, Inc.