即使在提供String.Empty之后,XML Serializer仍然添加默认命名空间

时间:2016-06-30 20:14:31

标签: c# xml serialization xml-serialization xmlserializer

我正在使用XmlSerializer来创建一些XML。但是,我在输出中得到了www.w3.org名称空间,我不想要它。我是我的序列化代码我包括该行 我认为xmlSerializerNameSpaceValue.Add(String.Empty, String.Empty);应该摆脱这个,但它似乎没有用,它只将命名空间值移动到我的BOM_Request部分。我将下面的代码和没有xmlSerializerNameSpaceValue.Add(String.Empty, String.Empty);的输出和输出都包括在内。我怎样才能摆脱这些命名空间?

序列化代码:

XmlSerializer serializer = new XmlSerializer(typeof(Request));
StringWriter stringWriter = new StringWriter();
String xmlRequest;

XmlSerializerNamespaces xmlSerializerNameSpaceValue = new                     
XmlSerializerNamespaces();
xmlSerializerNameSpaceValue.Add(String.Empty, String.Empty);
serializer.Serialize(stringWriter, request, xmlSerializerNameSpaceValue);

xmlRequest = stringWriter.ToString();
stringWriter.Close();

<?xml version="1.0" encoding="utf-8"?>
<Request xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <RequestHeader>
    <Field fieldName="RuleServTypeCode" value="FVAR" />
  </RequestHeader>
  <RequestPayload>
    <BOM_Request xsi:type="LossIncurredPayload" path="1" sequenceNum="1" requestSentDate="2016-06-30" validationType="LossInc" transactionId="10" decisionType="LossInc">
      <BOM_Policy path="1" sequenceNum="1" log_key="760" clm_ser_nbr="416006" />
    </BOM_Request>
  </RequestPayload>
</Request>

使用:

<?xml version="1.0" encoding="utf-8"?>
<Request>
  <RequestHeader>
    <Field fieldName="RuleServTypeCode" value="FVAR" />
  </RequestHeader>
  <RequestPayload>
    <BOM_Request d3p1:type="LossIncurredPayload" path="1" sequenceNum="1" requestSentDate="2016-06-30" validationType="LossInc" transactionId="10" decisionType="LossInc" xmlns:d3p1="http://www.w3.org/2001/XMLSchema-instance">
      <BOM_Policy path="1" sequenceNum="1" log_key="760" clm_ser_nbr="416006" />
    </BOM_Request>
  </RequestPayload>
</Request>

RequestPayload类:

[XmlIncludeAttribute(typeof(LossTrxPayload))]
[XmlIncludeAttribute(typeof(PremiumPayload))]
[XmlIncludeAttribute(typeof(LossIncurredPayload))]
public class RequestPayload
{
    [XmlElement]
    public List<Payload> BOM_Request { get; set; }
}

1 个答案:

答案 0 :(得分:0)

您的BOM_Request具有xsi:type属性,可将类型标识为LossIncurredPayload。您无法避免在此处指定xsi命名空间,因为该属性需要它。