如何控制XmlSerializer添加默认名称空间的位置

本文关键字:默认 空间 位置 添加 XmlSerializer 何控制 控制 | 更新日期: 2023-09-27 18:19:21

我试图控制在什么级别将默认命名空间添加到XmlSerializer的输出…

到目前为止,我已经……

<GetAccountDetailRequestStructure>
  <AccountRef xmlns="http://www.govtalk.gov.uk/NAC/GetAccountDetail">4026069</AccountRef>
  <AccountType xmlns="http://www.govtalk.gov.uk/NAC/GetAccountDetail">C</AccountType>
  <SelectionOptions xmlns="http://www.govtalk.gov.uk/NAC/GetAccountDetail">
    <FromDate>2000-01-01</FromDate>
    <ToDate>2015-10-23</ToDate>
    <IncludeAccountSummary>false</IncludeAccountSummary>
  </SelectionOptions>
</GetAccountDetailRequestStructure>
使用…

var ns = new XmlSerializerNamespaces();
ns.Add(string.Empty, "http://www.govtalk.gov.uk/NAC/GetAccountDetail");
var xs = new XmlSerializer(typeof(T));
xs.Serialize(xmlWriter, obj, ns);

但是我想要得到的是…

<GetAccountDetailRequestStructure xmlns="http://www.govtalk.gov.uk/NAC/GetAccountDetail">
  <AccountRef>4026069</AccountRef>
  <AccountType>C</AccountType>
  <SelectionOptions>
    <FromDate>2000-01-01</FromDate>
    <ToDate>2015-10-23</ToDate>
    <IncludeAccountSummary>false</IncludeAccountSummary>
  </SelectionOptions>
</GetAccountDetailRequestStructure>

我认为它相当于第一个XML示例

如何控制XmlSerializer添加默认名称空间的位置

也尝试将默认名称空间传递给XmlSerializer的构造函数:

const string defaultNamespace = "http://www.govtalk.gov.uk/NAC/GetAccountDetail";
var ns = new XmlSerializerNamespaces();
ns.Add(string.Empty, defaultNamespace);
// Note the 2nd constructor argument.
var xs = new XmlSerializer(typeof(T), defaultNamespace);
xs.Serialize(xmlWriter, obj, ns);