简体   繁体   English

如何控制XmlSerializer在何处添加默认名称空间

[英]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 ... 我试图控制将默认名称空间添加到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 我认为这等效于第一个XML示例

Try passing the default namespace to the constructor of XmlSerializer as well: 尝试将默认名称空间也传递给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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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