使用奇怪的命名空间序列化XML?

时间:2011-07-14 11:13:06

标签: c# xml vb.net serialization xml-serialization

问题:此XML内容序列化的类看起来如何?

<?xml version="1.0" encoding="utf-8"?>
<vcc:CreateTextSearchResponse xmlns:vcc="urn:veloconnect:catalog-1.1" xmlns:vct="urn:veloconnect:transaction-1.0">
  <vct:BuyersID>12345</vct:BuyersID>
  <vct:ResponseCode>200</vct:ResponseCode>
  <vct:TransactionID>225</vct:TransactionID>
  <vct:StatusCode>2</vct:StatusCode>
  <vct:IsTest>false</vct:IsTest>
  <vcc:TotalCount>3876</vcc:TotalCount>
</vcc:CreateTextSearchResponse>

如果我让它运行xsd.exe,则会产生错误。

我生成这个没问题:

<?xml version="1.0" encoding="utf-8"?>
<CreateTextSearchResponse>
  <BuyersID>15942</BuyersID>
  <ResponseCode>200</ResponseCode>
  <TransactionID>225</TransactionID>
  <StatusCode>2</StatusCode>
  <IsTest>false</IsTest>
  <TotalCount>3876</TotalCount>
</CreateTextSearchResponse>

只是我需要这些命名空间来反序列化它(以及稍后重新编译),所以我不能像这样(第三方Web服务需要它)...

2 个答案:

答案 0 :(得分:5)

像这样:

[XmlRoot(Namespace = CreateTextSearchResponse.CatalogNamespace)]
public class CreateTextSearchResponse
{
    public const string CatalogNamespace = "urn:veloconnect:catalog-1.1",
                TransactionNamespace = "urn:veloconnect:transaction-1.0";
    [XmlElement(Namespace=TransactionNamespace)]
    public int BuyersId { get; set; }
    [XmlElement(Namespace = TransactionNamespace)]
    public int ResponseCode { get; set; }
    [XmlElement(Namespace = TransactionNamespace)]
    public int TransactionID { get; set; }
    [XmlElement(Namespace = TransactionNamespace)]
    public int StatusCode { get; set; }
    [XmlElement(Namespace = TransactionNamespace)]
    public bool IsTest { get; set; }
    [XmlElement(Namespace = CatalogNamespace)]
    public int TotalCount { get; set; }
}

public static void Main()
{
    var ser = new XmlSerializer(typeof(CreateTextSearchResponse));
    var obj = new CreateTextSearchResponse
    {
        BuyersId = 12345,
        ResponseCode = 200,
        TransactionID = 225,
        StatusCode = 2,
        IsTest = false,
        TotalCount = 3876
    };
    XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
    ns.Add("vcc", CreateTextSearchResponse.CatalogNamespace);
    ns.Add("vct", CreateTextSearchResponse.TransactionNamespace);
    ser.Serialize(Console.Out, obj, ns);
}

答案 1 :(得分:-1)

遗憾的是,您的命名空间中存在Xml无法处理的特殊字符