6

I am trying to form an XML document which I will be using to send as over HTTPS to an API, however I have noticed that even though I have added an XDeclaration element to my XML the XDeclaration does not appear in the string that I return using xmlDoc.ToString() method.

Does anyone know if I am missing a particular setting or any reason why the <?xml version="1.0" encoding="UTF-8" ?> elements are not appearing?

xmlDoc = new XDocument(
            new XDeclaration("1.0", "UTF-8", "yes"),
            new XElement("NABTransactMessage",
                new XElement("MessageInfo",
                    new XElement("MessageID", "5167813675aa47d181a7c76979f2de00"),
                    new XElement("MessageTimeStamp", "20152701024752898882+000"),
                    new XElement("timeoutValue", 60),
                    new XElement("apiVersion", "spxml-4.2")
                ),
                new XElement("MerchantInfo",
                    new XElement("MerchantID", "XYZ0010"),
                    new XElement("password", "abcd1234")
                ),
                new XElement("RequestType", "Periodic"),
                new XElement("Periodic",
                    new XElement("PeriodicList", new XAttribute("count", 1),
                        new XElement("PeriodicItem", new XAttribute("ID", 1),
                            new XElement("actionType", "addcrn"),
                            new XElement("periodicType", 5),
                            new XElement("crn", "85c2960d-1422326872"),
                            new XElement("CreditCardInfo", 
                                new XElement("cardNumber", 4111111111111111),
                                new XElement("expiryDate", "08/20"),
                                new XElement("cvv", 123)
                            )
                        )
                    )
                )
            )
        );

return xmlDoc.ToString(SaveOptions.None);

Code to Send Request via HTTPS:

    public static string SendRequest(string requestContent, string requestContentType, string requestUrl)
    {
        try
        {
            var request = (HttpWebRequest)WebRequest.Create(requestUrl);
            byte[] bytes;

            bytes = System.Text.Encoding.UTF8.GetBytes(requestContent);

            request.ContentType = requestContentType + "; encoding='utf-8'";
            request.ContentLength = bytes.Length;
            request.Method = "POST";
            //request.Timeout = 5000;

            ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;

            using (var requestStream = request.GetRequestStream())
            {
                requestStream.Write(requestContent, 0, requestContent.Length);
            }

            using (var response = (HttpWebResponse)request.GetResponse())
            {
                using (var responseStream = response.GetResponseStream())
                {
                    return new StreamReader(responseStream).ReadToEnd();
                }
            }
        }

NOTES: xmlDoc.ToString() value is being passed to SendRequest() as the first parameter, requestContentType is being set to "text/xml"

Matthew Pigram
  • 1,400
  • 3
  • 25
  • 65

2 Answers2

15

XDocument.ToString() doesn't include the declaration. Instead, use XDocument.Save(), e.g.:

    public static string ToXml(this XDocument xDoc)
    {
        StringBuilder builder = new StringBuilder();
        using (TextWriter writer = new StringWriter(builder))
        {
            xDoc.Save(writer);
            return builder.ToString();
        }
    }

If specifically you need to make the encoding string say "UTF-8", see here: Force XDocument to write to String with UTF-8 encoding

Note that this extension is for XDocument, not XmlDocument which has OuterXml.

Jason Honingford
  • 540
  • 5
  • 17
dbc
  • 104,963
  • 20
  • 228
  • 340
0

Serializing to string can't preserve Utf-8 declaration as it will not be valid at that point - so it will be removed.

You need to save the data to stream if you need Utf-8 (default) encoding. Sample and more discussion - Serializing an object as UTF-8 XML in .NET.

Community
  • 1
  • 1
Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
  • I have updated my question, I am not sure how to convert to stream using my current way of sending data through the HTTP Request. – Matthew Pigram Jan 28 '15 at 02:37