Dan Atkinson
Dan Atkinson

Reputation: 11679

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.

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

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

Upvotes: 4

Views: 6933

Answers (1)

Marc Gravell
Marc Gravell

Reputation: 1062512

If you are talking about (xml) attributes (i.e. <foo bar="abc"/>), then you aren't talking about DataContractSerializer - so perhaps stick with the XmlType etc... something like:

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

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

Upvotes: 8

Related Questions