Question

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:­­enquiry@gis.nottscc.gov.uk­­"/> 
</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:enquiry@gis.nottscc.gov.uk";

         }

which outputs the xml as follows:

<ows:ContactInfo xlink:href="mailto:enquiry@gis.nottscc.gov.uk">
<ows:OnlineResource>mailto:enquiry@gis.nottscc.gov.uk</ows:OnlineResource>
</ows:ContactInfo>
Was it helpful?

Solution

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:enquiry@gis.nottscc.gov.uk";
 }

Output for this is ...

<ContactInfo>
  <OnlineResource href="mailto:enquiry@gis.nottscc.gov.uk" />
</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?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top