views:

82

answers:

1

I have a simple object I'm trying to serialize using DataContractSerializer.

In my unit test, I'm trying to verify the xml contains the right value for the product/sku node.

My product class:

[DataContract(Namespace = "http://foo.com/catalogue/")
partial class Product
{
   [DataMember(Name = "sku")]
   public virtual string ProductSKU
   {
      get { return _productSKU; }
      set
      {
         OnProductSKUChanging();
        _productSKU = value;
        OnProductSKUChanged();
      }
   }
}

Here's the method I'm testing:

public XDocument GetProductXML(Product product)
    {
        var serializer = new DataContractSerializer(typeof(Product));
        var document = new XDocument();

        using (var writer = document.CreateWriter())
        {
            serializer.WriteObject(writer, product);
            writer.Close();
        }

        return document;
    }

And here's my unit test:

[Test]
    public void Can_get_product_xml()
    {
        // Arrange
        var product = new Product {Id = 1, Name = "Foo Balls", ProductSKU = "Foo123"};
        var repository = new CatalogueRepository();
        var expectedProductSKU = "Foo123";

        // Act
        var xml = repository.GetProductXML(product);
        var actualProductSKU = xml.Element("product").Element("sku").Value;

        // Assert
        Assert.AreEqual(expectedProductSKU, actualProductSKU);
    }

The problem is that I get a Null reference when I try and access the xml elements, even though when I set a break point the var xml contains:

<product xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://foo.com catalogue/">
  <sku>Foo123</sku> 
</product>

Any ideas why this is not working? Do I need to parse the serialized stream before adding it to the XDocument?

+1  A: 

I would think the problem lies in the fact your XML document has a XML namespace xmlns="http://foo.com catalogue/", but when you select using Linq-to-XML, you're never using that namespace in any way, shape or form.

Also, the <product> tag is your XML root tag - you cannot reference that as an element.

Try something like this:

XNamespace ns = "http://foo.com/catalogue/";

var root = xml.Root;
var sku = root.Element(xns + "sku").Value;

If you want to be sure, first assign .Element() to a variable and check for != null

var sku = root.Element(xns + "sku");
if(sku != null)
{
   var skuValue = first.Value;
}

Hope that helps a bit !

marc_s
Ah, I thought it might be something to do with the namespace ... will try
mattRo55
Oh yes, that worked. Cheers Marc!
mattRo55
great ! Good to know it helped. Enjoy!
marc_s