1

I'm trying to deserialize xml below:

<venue href="http://SomeUrl">
   <location id="ABC"/>
   <title>Some title</title>
</venue>

When I wrap it with class like below XmlSerializer works like charm

[XmlRoot(ElementName = "venue")]
public class VenueModel
{
    [XmlElement("location")]
    public Location Location;

    [XmlElement("title")]
    public string Title;

    [XmlAttribute("href")]
    public string Href;
}

public class Location
{
    [XmlAttribute("id")]
    public string Id;
}

But in my opinion wrapping simple string from Location into separate class it's quite dull solution. What I would like to achieve is to create simpler flatten model like below:

[XmlRoot(ElementName = "venue")]
public class VenueModel2
{
    [SomeMagicAttribute]
    public string LocationId;

    [XmlElement("title")]
    public string Title;

    [XmlAttribute("href")]
    public string Href;
}

so first question? is it possible using C# System.Xml.Serialization? If it is, what is the magic attribute to get this data?

Misiakw
  • 902
  • 8
  • 28
  • In class location you are missing Text: [XmlText] public string Text { get; set; } Otherwise you cannot read the value in value. –  Feb 13 '17 at 12:49
  • location did'n have any text value. it contains only ID send as attribute. and this is the only thing it's designed for – Misiakw Feb 13 '17 at 12:57
  • In that case it should not be an attribute but the value of locationid. But I suppose you cannot change this? –  Feb 13 '17 at 13:00
  • yep. I know that it's dull but this is how it comes back from external API. and i don't want to use the same dull code in my solution. but i don't wand to add any logic to data models eiuther, so i don't want to add aditional getter/setter to get this IS as VenueModel property – Misiakw Feb 13 '17 at 13:02

1 Answers1

0

what I found is that first i need to apply xsl translation (as the one below) to input xml

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" encoding="utf-8" indent="no"/>
       <xsl:template match="/">
          <venue>
             <href><xsl:value-of select="/venue/@href" /></href>
             <locationId><xsl:value-of select="/venue/location/@id" /></locationId>
             <title><xsl:value-of select="/venue/title" /></title>
          </venue>
    </xsl:template>
</xsl:stylesheet>

and then output xml looks like this:

<venue>
   <href>SomeUrl</href>
   <locationId>ABC</locationId>
   <title>Some title</title>
</venue>

which than can be deserialised to the form i want it to be. and applyink this translations in C# code is described here: C# How to perform a live xslt transformation on an in memory object?

Community
  • 1
  • 1
Misiakw
  • 902
  • 8
  • 28