当尝试使用在根节点上包含 xmlns 属性的 RestSharp 将对象序列化为 XML 时,我收到以下异常:
无法将前缀“”从“”重新定义为“https://someurl.com ' 在同一个开始元素标记内。
我尝试序列化的对象只包含一个属性(目前),即 XmlNamespace:
[SerializeAs(Name = "root")]
public class Root
{
[SerializeAs(Name = "xmlns", Attribute = true)]
public String XmlNamespace { get; set; }
}
尝试将我的对象添加到请求主体时发生异常,如下所示:
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
我已经尝试使用 RestRequest 的 XmlNamespace 属性以及为 RestRequest 实例化一个新的 XmlSerializer,但是这些都没有按照我尝试访问的 API 的要求将 namespace 附加到根节点。有人碰巧知道如何在 RestSharp 中正确序列化 xmlns 属性吗?
最佳答案
我最终找到了答案。看起来我对请求和 XmlSerializer 级别的 XmlNamespace 属性的存在感到困惑。对于遇到此问题的任何其他人,解决方法是在调用 AddBody 方法时定义命名空间,如下所示:
request.AddBody(requestBody, "https://someurl.com");
关于c# - Restsharp - 尝试序列化根节点上的 xmlns 属性时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29420593/