Copy single element of XML document being created by XMLWriter

626 Views Asked by At

My C# application has method that takes a list of objects (inputList) as parameter, it creates an XML string using the TextWriter and XMLWriter with the code below and submits to a webservice.

using (TextWriter writer = new Utf8StringWriter())
{
    using (XmlWriter xw = XmlWriter.Create(writer, settings))
    {
        xw.WriteStartElement("submission");
        xw.WriteElementString("version", XMLversion);
        xw.WriteElementString("user", USER_NAME);

        foreach (var obj in inputList)
        {
            xw.WriteStartElement("node");
            xw.WriteElementString("data1", obj.data1.ToString());
            xw.WriteElementString("data2", obj.data2.ToString());
            xw.WriteElementString("data3", obj.data3.ToString());
            xw.WriteElementString("data4", obj.data4.ToString()); 
            xw.WriteEndElement();
        }

    }
    xmlFile = writer.ToString();
}

One of the requirements to to log the submission for each item in the list individual. So I'd like to know if there's a more efficient way to create a string of the XML node within the foreach loop?

I've considered using the XMLReader with the string afterwards but that's a whole new process and while I know I can create it manually, and am happy to do so, I am open to other suggestions. In essence, I'm looking for an efficient technique to generate a string as illustrated below:

<node>
    <data1>obj.data1.ToString()</data1>
    <data2>obj.data2.ToString()</data2>
    <data3>obj.data3.ToString()</data3>
    <data4>obj.data4.ToString()</data4>
</node>
1

There are 1 best solutions below

3
Jono On BEST ANSWER

Your XML document does not seem large enough to warrant using XmlWriter and XmlReader. Assuming it can fit comfortably in memory then I'd use XmlDocument, which allows you to get a node's OuterXml (or InnerXml if you prefer) as a string.

var document = new XmlDocument();

var submission = document.CreateElement("submission");
document.AppendChild(submission);

var version = document.CreateElement("version");
submission.AppendChild(version);
var versionText = document.CreateTextNode(XMLversion);
version.AppendChild(versionText);

var user = document.CreateElement("user");
submission.AppendChild(user);
var userText = document.CreateTextNode(USER_NAME);
user.AppendChild(userText);

foreach (var obj in inputList)
{
    var node = document.CreateElement("node");
    submission.AppendChild(node);

    var data1 = document.CreateElement("data1");
    node.AppendChild(data1);
    var data1Text = document.CreateTextNode(obj.data1.ToString());
    data1.AppendChild(data1Text);

    // TODO: repeat last 4 lines for data2, data3 and data4

    Console.WriteLine(node.OuterXml);
}

Console.WriteLine(document.OuterXml);