简体   繁体   English

如何使用XML Serializer将多个xml命名空间应用于同一个类

[英]How to apply multiple xml namespaces to the same class with the XML Serializer

I'm trying to generate a proxy class with WCF which, when serialized, converts and instance of the class below into the XML below. 我正在尝试使用WCF生成代理类,当序列化时,将下面的类和实例转换为下面的XML。

However, when I try to apply namespaces to the classes, they're inserted incorrectly, or not at all. 但是,当我尝试将命名空间应用于类时,它们被错误地插入,或者根本不插入。

What am I doing wrong? 我究竟做错了什么? How can I fix this? 我怎样才能解决这个问题?

Many thanks in advance. 提前谢谢了。

Class Structure: 班级结构:

[XmlRoot]
public class Request
{
  public int Id

  public Name Name {get;set;}
}

[XmlRoot]
public class Name
{
  [XmlAttribute]
  public bool test {get;set;}

  public string FirstName {get;set;}

  public string LastName {get;set;}
}

Desired XML structure (superfluous XML trimmed) : 期望的XML结构(多余的XML修剪)

<x1:Request xmlns:x1="Data/Main" xmlns:x2="Data/All">
  <x2:Id>0</x2:Id>
  <x2:Name test="true">
    <x2:FirstName>Dan</x2:FirstName>
    <x2:LastName>Atkinson</x2:LastName>
  </x2:Name>
</x1:Request>

If you are talking about (xml) attributes (ie <foo bar="abc"/> ), then you aren't talking about DataContractSerializer - so perhaps stick with the XmlType etc... something like: 如果你在谈论(xml)属性(即<foo bar="abc"/> ),那么你不是在谈论DataContractSerializer - 所以也许坚持使用XmlType等...类似于:

[XmlRoot(Namespace="Data/Main")]
public class Request {
  [XmlElement(Namespace = "Data/All")]
  public int Id { get; set; }
  [XmlElement(Namespace="Data/All")]
  public Name Name {get;set;}
}

[XmlType(Namespace="Data/All")]
public class Name {
  [XmlAttribute("test")]
  public bool Test {get;set;}
  public string FirstName {get;set;}
  public string LastName {get;set;}
}

That doesn't have the aliases - but it seems to be correct, at least... 那没有别名 - 但它似乎是正确的,至少......

Merge the attributes above with "Guard"'s XmlSerializerNamespaces code and it should be there... 将上面的属性与“Guard”的XmlSerializerNamespaces代码合并,它应该在那里......

(credit here to "Guard", but this is wiki anyway...) (这里称为“警卫”,但无论如何这是维基...)

    Request req = new Request {
        Id = 0, Name = new Name {
            Test = true, FirstName = "Dan", LastName = "Atkinson"
        }
    };
    XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
    ns.Add("x1", "Data/Main");
    ns.Add("x2", "Data/All");
    new XmlSerializer(req.GetType()).Serialize(Console.Out, req,ns);

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

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