简体   繁体   中英

Restsharp - Error attempting to serialize xmlns attribute on root node

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?

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"); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM