Euston
Euston

Reputation: 81

Using XMLSerializer to add attributes to a Class Member

I am attempting to write a WCF service which uses XmlSerialzer to output the xml. I need a specific xml output which is why I am not using DataContract Seriailzer. Specifically I am writing a catalogue service web(csw) which has a defined schema etc.

I have been trying to write the classes first and then test what XML is being outputted. This is rather tedious and I may switch to the xsd utility. What I would like to know is can I add xml attributes to other class members or will those decorated xmlattributes only be added to the root element i.e the class name? There seems to be flexibility issues compared to writing the CML by hand using XDocument. Also every time I need to nest elements (not collections) It seems I need to create a new class? Is that right?

The output xml I need is:

<ows:ContactInfo> 
<ows:OnlineResource 
   xlink:href="mailto:­­[email protected]­­"/> 
</ows:ContactInfo>

Here is my class:

   public class ContactInfo
       {
            [XmlElement] 
            public string OnlineResource = "";        

            [XmlElementAttribute(ElementName = "OnlineResource",Namespace = "http://www.w3.org /1999/xlink")]
            public string href = "mailto:[email protected]";

         }

which outputs the xml as follows:

<ows:ContactInfo xlink:href="mailto:[email protected]">
<ows:OnlineResource>mailto:[email protected]</ows:OnlineResource>
</ows:ContactInfo>

Upvotes: 0

Views: 2548

Answers (1)

iDevForFun
iDevForFun

Reputation: 988

You will need to change your object model to make this happen ... try something like this ...

 [XmlType("ContactInfo")]
 public class ContactInfo
 {
    [XmlElement("OnlineResource")]
    public OnlineResource Resource { get; set; }
 }

 [XmlType("OnlineResource")]
 public class OnlineResource
 {
     [XmlAttribute("href")]
     public string href = "mailto:[email protected]";
 }

Output for this is ...

<ContactInfo>
  <OnlineResource href="mailto:[email protected]" />
</ContactInfo>

Naturally you need to adjust to get your namespaces etc but this is heading in the right direction ... hope it helps :)

Yes .. when you nest elements you will need a new class ... this makes sense? How would a primitive result in a nested set of values?

Upvotes: 2

Related Questions