2

When attempting to serialize an object to XML using RestSharp that contains an xmlns attribute on the root node, I receive the following exception:

The prefix '' cannot be redefined from '' to 'https://someurl.com' within the same start element tag.

The object I'm attempting to serialize only contains one property (for now), the XmlNamespace:

[SerializeAs(Name = "root")]
public class Root
{
    [SerializeAs(Name = "xmlns", Attribute = true)] 
    public String XmlNamespace { get; set; }
}

The exception occurs when trying to add my object to the request body, like so:

Root requestBody = new Root();

requestBody.XmlNamespace = "https://someurl.com";

var request = new RestRequest();

request.Method = Method.POST;
request.Resource = "orders";
request.RequestFormat = DataFormat.Xml;

request.AddBody(requestBody); // exception occurs here

I've tried using the XmlNamespace property of the RestRequest as well as instantiating a new XmlSerializer for the RestRequest, but neither of these have appended the namespace to the root node as required by the API I'm attempting to access. Does anybody happen to know how to properly serialize an xmlns attribute in RestSharp?

1
  • You need to use the namespace when creating elements, you can't just append to the root and change the element namespace. Commented Apr 2, 2015 at 19:11

1 Answer 1

3

I wound up finding the answer. It looks like I was thrown off by the presence of XmlNamespace properties at the request and XmlSerializer levels. For anybody else that runs into this issue, the fix was to define the namespace when calling the AddBody method as follows:

request.AddBody(requestBody, "https://someurl.com"); 
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.