7

I am using the code below (simplified for this example) to post data to a SharePoint list

StringBuilder customerDoc = new StringBuilder();

customerDoc.Append("<Method ID='1' Cmd='New'>");
customerDoc.Append("<Field Name='Name'>" + Name + "</Field>");
customerDoc.Append("<Field Name='Age'>" + age + "</Field>");
customerDoc.Append("<Field Name='City'>" + city + "</Field>");
customerDoc.Append("<Field Name='Country'>" + country + "</Field>");

customerDoc.Append("</Method>");

XmlDocument xDoc = new XmlDocument();
XmlElement xBatch = xDoc.CreateElement("Batch");
xBatch.SetAttribute("OnError", "Continue");

xBatch.InnerXml = sb_method.ToString();

XmlNode xn_return = sharePoint.listsObj.UpdateListItems(ConfigurationManager.AppSettings["SaveCustomer"].ToString(), xBatch);

As you can see I am using a stringbuilder which isn't ideal so I wonder what I should use instead to create an XML string?

Thanks in advance.

Nick
  • 1,489
  • 4
  • 14
  • 10
  • what's problem you facing with stringBuilder? – Hukam Mar 29 '11 at 07:50
  • People seeem to be adverse to stringbuilders in general when it comes to creating xml documents/strings. It works but I wanted to check if I could improve the coding standard, maybe I am wrong though – Nick Mar 29 '11 at 07:52
  • try stringwriter check the difference here http://stackoverflow.com/q/602279/377996 – Hukam Mar 29 '11 at 08:00
  • 1
    One simple reason not to use string manipulation: that code will throw an exception if `Name` contains an ampersand. – Robert Rossney Mar 29 '11 at 17:27

8 Answers8

21

You could use Linq to XML, please check out something like: http://www.hookedonlinq.com/LINQtoXML5MinuteOverview.ashx.

For example, this code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Dynamic;
using System.Xml.Linq;

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            String name = "Morten";
            Int32 age = 30;
            String city = "Copenhagen";
            String country = "Denmark";

            XElement xml = new XElement("Method", 
                new XAttribute("ID", 1), 
                new XAttribute("Cmd", "New"),
                new XElement("Field", 
                    new XAttribute("Name", "Name"), 
                    name),
                new XElement("Field", 
                    new XAttribute("Name", "Age"), 
                    age),
                new XElement("Field", 
                    new XAttribute("Name", "City"), 
                    city),
                new XElement("Field", 
                    new XAttribute("Name", "Country"), 
                    country)
            );

            Console.WriteLine(xml);
            Console.ReadKey();
        }
    }
}

Will output:

<Method ID="1" Cmd="New">
  <Field Name="Name">Morten</Field>
  <Field Name="Age">30</Field>
  <Field Name="City">Copenhagen</Field>
  <Field Name="Country">Denmark</Field>
</Method>
Maate
  • 1,000
  • 1
  • 6
  • 15
  • Hi, maybe I simplified my example too much, I actually have a condtion for checking if the customer already exist or not. How could I alter your code to cater for "if (!String.IsNullOrEmpty(customerId)) { sb_method.Append(""); sb_method.Append("" + customerId + ""); } else { sb_method.Append(""); }" – Nick Mar 29 '11 at 08:29
  • Hi, I don't know how to put my whole answer with code into this comment - so I've posted it in the bottom of this question as a new answer instead. – Maate Mar 29 '11 at 08:37
10
  1. Create a class that mimics your XML schema.
  2. Instantiate the class and fill its properties (attributes, elements)
  3. Use XmlSerialization to generate an XML fragment either as a string or a stream.

d

public class Method
{
  [XmlAttribute()]
  public int ID {get;set;}

  [XmlAttribute()]
  public string Cmd {get;set;}

  public string Name {get;set;}
  public int Age {get;set;}
  public string City {get;set;}
  public string Country {get;set;}
}

public class Batch
{
  public Method Method { get; set; }
}

public static string ToXml(object Doc)
{
  try
  {
    // Save to XML string
    XmlSerializer ser = new XmlSerializer(Doc.GetType());
    var sb = new StringBuilder();
    using (var writer = XmlWriter.Create(sb))
    {
      ser.Serialize(writer, Doc);
    }
    return sb.ToString();
  }
  catch (Exception ex)
  { // Weird!
    ProcessException();
  }
}

var batch = new Batch();
batch.Method = new Method { ID=..., Cmd=..., ...};

var xml = ToXml(batch);
Serge Wautier
  • 21,494
  • 13
  • 69
  • 110
3

If your writing xml why not use the forward only XmlWriter? http://msdn.microsoft.com/en-us/library/system.xml.xmlwriter.aspx it's designed for creating the xml structure.

Scott Reed
  • 501
  • 1
  • 5
  • 18
3

you can generate xml more dynamically by breaking it up like the code below. Here, I use the .Add() method to append more attributes or alements.

Br. Morten

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Dynamic;
using System.Xml.Linq;

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            String name = "Morten";
            Int32 age = 30;
            String city = "Copenhagen";
            String country = "Denmark";

            String customerId = "100";

            XElement xml = new XElement("Method");
            if (!String.IsNullOrEmpty(customerId))
            {
                xml.Add(new XAttribute("ID", 1), new XAttribute("Cmd", "Update"));
            }
            else
            {
                xml.Add(new XAttribute("ID", customerId),new XAttribute("Cmd", "New"));
            }

            xml.Add(
                new XElement("Field", 
                    new XAttribute("Name", "Name"), 
                    name),
                new XElement("Field", 
                    new XAttribute("Name", "Age"), 
                    age),
                new XElement("Field", 
                    new XAttribute("Name", "City"), 
                    city),
                new XElement("Field", 
                    new XAttribute("Name", "Country"), 
                    country)
            );

            Console.WriteLine(xml);
            Console.ReadKey();
        }
    }
}

This code outputs:

<Method ID="1" Cmd="Update">
  <Field Name="Name">Morten</Field>
  <Field Name="Age">30</Field>
  <Field Name="City">Copenhagen</Field>
  <Field Name="Country">Denmark</Field>
</Method>
Maate
  • 1,000
  • 1
  • 6
  • 15
1

If that's an option for you, you might want to use VB.NET for this part of your project. It allows LINQ to XML objects to be created in a very concise way:

Dim xml As XElement = <Method ID="1" Cmd="New">
                          <Field Name="Name"><%= Name %></Field>
                          <Field Name="Age"><%= age %></Field>
                          <Field Name="City"><%= city %></Field>
                          <Field Name="Country"><%= country %></Field>
                      </Method>
Heinzi
  • 167,459
  • 57
  • 363
  • 519
0

You should be able to use System.Xml.XmlDocument. Full details can be found on MSDN but it's pretty easy to get to grips with and is designed specifically for writing XML docs.

AndyM
  • 1,148
  • 1
  • 10
  • 19
0

If you already used the api of System.Xml to create the XBatch element why don't you use it for all your xml fragment?

    private XmlElement CreateXmlDoc(string name, int age, string city, string country)
    {
        XmlDocument xDoc = new XmlDocument();
        XmlElement xBatch = xDoc.CreateElement("Batch");
        xBatch.SetAttribute("OnError", "Continue");
        xDoc.AppendChild(xBatch);

        XmlElement method = xDoc.CreateElement("Method");
        method.SetAttribute("ID", "1");
        method.SetAttribute("Cmd", "New");
        xBatch.AppendChild(method);

        method.AppendChild(createFieldElement(xDoc, "Name", name));
        method.AppendChild(createFieldElement(xDoc, "Age", name));
        method.AppendChild(createFieldElement(xDoc, "City", name));
        method.AppendChild(createFieldElement(xDoc, "Country", name));

        return xBatch;
    }

    private XmlElement createFieldElement(XmlDocument doc, string name, string value) 
    {
        XmlElement field = doc.CreateElement("Field");
        field.SetAttribute("Name", name);
        field.Value = value;
        return field;
    }
bruno conde
  • 47,767
  • 15
  • 98
  • 117
-1
    Dim sb As New StringBuilder()
    Dim sb1 As New StringBuilder()
    Dim a As String
    Dim ds As New DataSet()
    sb1.Append("<HEAD ")
    sb1.AppendFormat("invoiceno={0}{1}{0}", Chr(34), invoiceno)
    sb1.AppendFormat(" customercode={0}{1}{0}", Chr(34), Cuscode)
    sb1.AppendFormat(" invDate={0}{1}{0}", Chr(34), invdate)
    sb1.Append(" />")
    a = sb1.ToString()
    sb.Append("<SAVE>")
    For Each dr In dt.Rows
        sb.AppendFormat("<INVOIEC No ={0}{1}{0}", Chr(34), dr("No"), Chr(34))
        sb.AppendFormat(" ItemCode ={0}{1}{0}", Chr(34), dr("ItemCode"), Chr(34))
        sb.AppendFormat(" Qty ={0}{1}{0}", Chr(34), dr("Qty"), Chr(34))
        sb.AppendFormat(" Rate = {0}{1}{0}", Chr(34), dr("Rate"), Chr(34))
        sb.AppendFormat(" Amount = {0}{1}{0}", Chr(34), dr("Amount"), Chr(34))
        sb.AppendFormat(" />")
    Next
    sb.Append("</SAVE>")
    a = sb.ToString()
    Return INVDL.save(sb1, sb, "usp_SaveInvoice")
rayryeng
  • 102,964
  • 22
  • 184
  • 193
  • 1
    Usually code dumping answers are discouraged. It would be nice to **include** a brief description of what's going on in the above code, and why you decided to make those design choices in creating the code. Remember, you're not only answering the question to help the question poser, but you're also posting for future users who may encounter the same problem. Being verbose in your answer goes a long way. – rayryeng Mar 23 '15 at 21:04