views:

212

answers:

1

Hey!

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>
+3  A: 

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);
Marc Gravell
Mark, I have tried this one in my many tests and the problem is that the service that I'm sending messages explicitly requires the x1 and x2 aliases, and errors if it doesn't find them.
Dan Atkinson
@Marc: I was going to add an answer clarifying that [Xml] Attributes != [DataContract], but it would be better if you'd edit your correct answer to say so.
John Saunders
@Dan: You should complain to the creators of that service that they are violating the XML standards. Prefixes don't matter in XML.
John Saunders
@Marc, you mentioned "Guard"'s XmlSerializerNamespaces code. Where is this? Is that the code below?
Dan Atkinson
Scrub that last one, I've sorted it. Thank you Marc and John for your speedy responses!
Dan Atkinson
@Dan - sorry, left the keyboard ;-p Guard deleted his reply, but yes: the XmlSerializerNamespaces stuff...
Marc Gravell