简体   繁体   中英

How to control where the default namespace is added by the XmlSerializer

I'm trying to control at what level the default namespace is added to the output of the XmlSerializer ...

So far I've got ...

<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>

using ...

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

but what I'm trying to get is ...

<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>

which I believe is an equivalent to the first XML example

Try passing the default namespace to the constructor of XmlSerializer as well:

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

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