0

I have an xml document that was build from classes then serialized. Later, I have deserialized the data and have used the same class structure. I currently have a variable that is filled with objects. What I need now, is the ability to search each object for a specific value, if the value exists, append new data as a child. I have poked around with Reflection and the GetValue property in .NET but have become rather confused. Some sample code is below.

Thank you.

public class Root
{
    [XmlElement("Product")]
    public List<Product> Product { get; set; }

    [XmlElement("Modification")]
    public List<Modification> Modification { get; set; }
}

public class Product
{
    public string ProductID { get; set; }
    public string ProductName { get; set; }
    public List<ColorVariants> ColorVariants { get; set;}
    public List<FeatureAddOns> FeatureAddOns { get; set; }
}

DataTable DTFeatureAddOn = new DataTable();
DTFeatureAddOn.Columns.Add("ProductID", typeof(String));
DTFeatureAddOn.Columns.Add("ProductName", typeof(String));

DataRow drDTFeatureAddOn = DTFeatureAddOn.NewRow();
drDTFeatureAddOn["ProductID"] = "ProductID";
drDTFeatureAddOn["ProductName"] = "ProductName";

DTFeatureAddOn.Rows.Add(drDTFeatureAddOn);

catalogFeed = DeserializeCatalogFeed();

if (DTFeatureAddOn.Rows.Count > 0)
{
    foreach (DataRow row in DTFeatureAddOn.Rows)
{
//a. For each unique ProductID, first check to make sure the does not exist – if NOT then create
    List<int> ProductIDList = new List<int>();
    PropertyInformation pinfo = typeof(Root).GetProperty("ProductID");
    //foreach (catalogFeed.Product
    //b. For each PlacementCode, create a structure FeatureAddOn below that ProductID.  This may results into a list of FeatureAddons for a given ProductID
    }


SerializeToXML(catalogFeed, DeltaCatalogFeedUpload.FileName);
}

    public static void SerializeToXML(Root rootNode, string FileName)
    {
        XmlSerializer serializer = new XmlSerializer(typeof(Root));
        TextWriter tw = new StreamWriter(FileName);
        serializer.Serialize(tw, rootNode);
        tw.Close();
    }

    public static Root DeserializeFromXML()
    {
        XmlSerializer deserializer = new XmlSerializer(typeof(Root));
        TextReader textReader = new StreamReader(DeltaCatalogFeedUpload.FileName);
        Root nodes;
        nodes = (Root)deserializer.Deserialize(textReader);
        textReader.Close();

        return nodes;
    }

    public static Root DeserializeCatalogFeed()
    {
        Root root = new Root();
        try
        {

            FileInfo fInfo = new FileInfo(DeltaCatalogFeedUpload.FileName);
            if (fInfo.Exists)
            {

                root = DeserializeFromXML();

            }
            else
            {
                root.Product = new List<Product>();
                root.Modification = new List<Modification>();
                root.PlacementCodeList = new List<PlacementCodeList>();
                root.AssociatedSKU = new List<AssociatedSKU>();
                root.FontStyle = new List<FontStyle>();
                root.FontSize = new List<FontSize>();
                root.FontType = new List<FontType>();
                root.Alignment = new List<Alignment>();
                root.ThreadColor = new List<ThreadColor>();                    
                root.Category = new List<Category>();
                root.ProductLine = new List<ProductLine>();
                root.ProductStock = new List<ProductStock>();
                root.ProductFiber = new List<ProductFiber>();                    
                root.ProductFabric = new List<ProductFabric>();
                root.Season = new List<Season>();
            }
        }
        catch (Exception e)
        {
            // do something with the error but always return a price list
            root.Product = new List<Product>();
            root.Modification = new List<Modification>();
            root.PlacementCodeList = new List<PlacementCodeList>();
            root.AssociatedSKU = new List<AssociatedSKU>();
            root.FontStyle = new List<FontStyle>();
            root.FontSize = new List<FontSize>();
            root.FontType = new List<FontType>();
            root.Alignment = new List<Alignment>();
            root.ThreadColor = new List<ThreadColor>();
            root.Category = new List<Category>();
            root.ProductLine = new List<ProductLine>();
            root.ProductStock = new List<ProductStock>();
            root.ProductFiber = new List<ProductFiber>();
            root.ProductFabric = new List<ProductFabric>();
            root.Season = new List<Season>();
        }
        return root;
    }
3
  • What is the type of catalogFeed? Your question doesn't say anything about the use of a DataTable, so your code doesn't seem to match the question. Could you show the code you're using to deserialize the xml? Feb 13, 2015 at 16:41
  • I have added the code for the serialize and deserialize functions. The DataTable contains incoming data that I need to add to the XML. I apologize if I am not being clear. Basically, I want to get ID's from the DataTable, Check "catalogFeed" for the ID's. If they are there, Add the new data as nodes of FeatureAddOns in Product.
    – joerdie
    Feb 13, 2015 at 17:36
  • That helps. I'll post an answer soon. Feb 13, 2015 at 19:19

1 Answer 1

0

It sounds like you're looking for LINQ to Objects.

catalogFeed.Product is a list of Product objects (List<Product>). Personally, I would have named that property Products, but that would just be for readability.

Assuming from your code that Product class has a property named ProductID and that is what you want to match on.

I would create a dictionary of Product objects with ProductID as the key. Do this via the ToDictionary LINQ method like this:

var productLookup = catalogFeed.Product.ToDictionary(p => p.ProductID);

Then inside your loop through the data table, you can locate the matching product in the dictionary.

foreach (DataRow row in DTFeatureAddOn.Rows)
{
    var productId = row["ProductID"];
    if (productLookup.ContainsKey(productId))
    {
        var matchingProduct = productLookup[productId];
        // get whatever you need out of the matching product.
    }
}

You could use a LINQ query to locate the matching product on each iteration through the loop, but using the ToDictionary approach means that the scan of the list only happens once. It's essentially creating an in-memory index so you can quickly find the object you're looking for without scanning the whole list each time, but if you did want to do that, finding a single matching product by ProductID with FirstOrDefault would look like this:

var matchingProduct = catalogFeed.Product.FirstOrDefault(p => p.ProductID = desiredProductID);

If there was no match, then matchingProduct would be null.

3
  • That was rather helpful thank you. I am getting the error "An item with the same key has already been added." when I try running ToDictionary. Assuming I get that to work, would I be able to add nodes that already exist using this method? I can kind of see how I would, inside your if statement, append a new instance of the list to the node?
    – joerdie
    Feb 13, 2015 at 20:41
  • Oh, ToDictionary assumes that the Key is unique. Do you have duplicate ProductIDs? i.e. more than one Product in the list with the same ProductID? Maybe you could add a bit more info to your question regarding the shape of your data. Feb 13, 2015 at 20:49
  • In some cases, the ID's will be the same yes. Sadly, I do not have control over the incoming XML that I am adding to. I was able to get something similar to your second example to work "catalogFeed.Product.Exists(x => x.ProductID == row["ProductID"].ToString())" It returns a bool that I can use to decide if I am adding a new node or adding a child node. I am still fighting with how I would add that child node however.
    – joerdie
    Feb 13, 2015 at 20:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.