Orion
Orion

Reputation: 452

Output each Property as XElement

How do I get each property as an XElement?

I'm basically trying to convert an IEnumerable object to XML in a web service.

Here is my code I'm trying to convert to XML.

        using (var db = new nopMass())
        {
            var cats = db.Categories
                        .Where(x => x.Deleted == false
                                    && x.Published == true)
                        .OrderBy(x => x.DisplayOrder)
                        .AsEnumerable()
                        .Select(cat => new Category
                        {
                            Id = cat.Id,
                            Name = cat.Name,
                            Description = cat.Description,
                            MetaKeywords = cat.MetaKeywords,
                            MetaDescription = cat.MetaDescription,
                            MetaTitle = cat.MetaTitle,

                            PictureId = cat.PictureId,

                            DisplayOrder = cat.DisplayOrder,
                            CreatedOnUtc = cat.CreatedOnUtc,
                            Product_Category_Mapping = cat.Product_Category_Mapping,
                            ParentCategoryId = cat.ParentCategoryId,
                        })
                        .ToArray();


            XElement Configuration = new XElement("Collection",
                  cats
                  .ToList()
                  .Select(c => new XElement("Element", c)));

            return Configuration.ToString();
        }

Edit

Category Class Definition (Using EntityFramework 6 Code First)

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.Spatial;
[Table("Category")]
public partial class Category
{
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
    public Category()
    {
        Product_Category_Mapping = new HashSet<Product_Category_Mapping>();
        Discounts = new HashSet<Discount>();
    }

    public int Id { get; set; }

    [Required]
    [StringLength(400)]
    public string Name { get; set; }

    public string Description { get; set; }

    public int CategoryTemplateId { get; set; }

    [StringLength(400)]
    public string MetaKeywords { get; set; }

    public string MetaDescription { get; set; }

    [StringLength(400)]
    public string MetaTitle { get; set; }

    public int ParentCategoryId { get; set; }

    public int PictureId { get; set; }

    public int PageSize { get; set; }

    public bool AllowCustomersToSelectPageSize { get; set; }

    [StringLength(200)]
    public string PageSizeOptions { get; set; }

    [StringLength(400)]
    public string PriceRanges { get; set; }

    public bool ShowOnHomePage { get; set; }

    public bool IncludeInTopMenu { get; set; }

    public bool HasDiscountsApplied { get; set; }

    public bool SubjectToAcl { get; set; }

    public bool LimitedToStores { get; set; }

    public bool Published { get; set; }

    public bool Deleted { get; set; }

    public int DisplayOrder { get; set; }

    public DateTime CreatedOnUtc { get; set; }

    public DateTime UpdatedOnUtc { get; set; }

Edit 2

Discount Class Difinition

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.Spatial;

[Table("Discount")]
public partial class Discount
{
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
    public Discount()
    {
        DiscountRequirements = new HashSet<DiscountRequirement>();
        DiscountUsageHistories = new HashSet<DiscountUsageHistory>();
        Categories = new HashSet<Category>();
        Products = new HashSet<Product>();
    }

    public int Id { get; set; }

    [Required]
    [StringLength(200)]
    public string Name { get; set; }

    public int DiscountTypeId { get; set; }

    public bool UsePercentage { get; set; }

    public decimal DiscountPercentage { get; set; }

    public decimal DiscountAmount { get; set; }

    public DateTime? StartDateUtc { get; set; }

    public DateTime? EndDateUtc { get; set; }

    public bool RequiresCouponCode { get; set; }

    [StringLength(100)]
    public string CouponCode { get; set; }

    public int DiscountLimitationId { get; set; }

    public int LimitationTimes { get; set; }

    public int? MaximumDiscountedQuantity { get; set; }

    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<DiscountRequirement> DiscountRequirements { get; set; }

    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<DiscountUsageHistory> DiscountUsageHistories { get; set; }

    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<Category> Categories { get; set; }

    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<Product> Products { get; set; }
}

Product_Category_Mapping Class Definition

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.Spatial;

public partial class Product_Category_Mapping
{
    public int Id { get; set; }

    public int ProductId { get; set; }

    public int CategoryId { get; set; }

    public bool IsFeaturedProduct { get; set; }

    public int DisplayOrder { get; set; }

    public virtual Category Category { get; set; }

    public virtual Product Product { get; set; }
}

Upvotes: 0

Views: 67

Answers (3)

Orion
Orion

Reputation: 452

This is the best solution I could come up with. It works, so going to accept it as my answer.

    // GETAll api/category
    [WebMethod]
    public string GetAllCategories()
    {
        using (var db = new nopMass())
        {
            var cats = db.Categories
                        .Where(x => x.ParentCategoryId == 1
                                    && x.Deleted == false
                                    && x.Published == true)
                        .OrderBy(c => c.ParentCategoryId)
                        .ThenBy(c => c.DisplayOrder)
                        .AsEnumerable()
                        .Select(cat => new Category
                        {
                            Id = cat.Id,
                            Name = cat.Name,
                            Description = cat.Description,
                            MetaKeywords = cat.MetaKeywords,
                            MetaDescription = cat.MetaDescription,
                            MetaTitle = cat.MetaTitle,
                            PictureId = cat.PictureId,
                            DisplayOrder = cat.DisplayOrder,
                            CreatedOnUtc = cat.CreatedOnUtc,
                            Product_Category_Mapping = cat.Product_Category_Mapping,
                            ParentCategoryId = cat.ParentCategoryId,
                        })
                        .ToList();

            string XML = "";

            #region BuildXMLString

            XML += "<Collection>";
            foreach (var item in cats)
            {
                XML += "<Category>";

                XML += "<Id>";
                XML += item.Id.ToString();
                XML += "</Id>";

                XML += "<Name>";
                XML += item.Name;
                XML += "</Name>";

                XML += "<Description>";
                XML += item.Description;
                XML += "</Description>";

                XML += "<MetaKeywords>";
                XML += item.MetaKeywords;
                XML += "</MetaKeywords>";

                XML += "<MetaDescription>";
                XML += item.MetaDescription;
                XML += "</MetaDescription>";

                XML += "<MetaTitle>";
                XML += item.MetaTitle;
                XML += "</MetaTitle>";

                XML += "<PictureUrl>";
                try
                {
                    XML += GetPictureUrl(item.PictureId);
                }
                catch { }
                XML += "</PictureUrl>";

                XML += "<DisplayOrder>";
                XML += item.DisplayOrder.ToString();
                XML += "</DisplayOrder>";

                XML += "<CreatedOnUtc>";
                XML += item.CreatedOnUtc.ToString();
                XML += "</CreatedOnUtc>";

                XML += "<ParentCategoryId>";
                XML += item.ParentCategoryId.ToString();
                XML += "</ParentCategoryId>";

                XML += "</Category>";
            }
            XML += "</Collection>";

            #endregion

            return XML;

        }
    }

Upvotes: 0

Richard Schneider
Richard Schneider

Reputation: 35477

Use the OuterXml property of the node. It will return exactly what you want.

 return Configuration.OuterXml;

Upvotes: 1

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236188

Thus you actually need xml string, easiest way will be simple xml serialization. E.g. if you have following categories:

var cats = new List<Category> {
    new Category { Id = 1, Name = "Auto", Description = "blah-blah-blah" },
    new Category { Id = 2, Name = "Moto", Description = "bikes!" }
};

Serialization will look like

var serializer = new XmlSerializer(typeof(List<Category>), 
                                   new XmlRootAttribute("Categories"));
using (var writer = new StringWriter())
{
    serializer.Serialize(writer, cats);
    return writer.ToString();
}

Output:

<?xml version="1.0" encoding="utf-16"?>
<Categories xmlns:xsd="http://www.w3.org/2001/XMLSchema"
            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <Category>
    <Id>1</Id>
    <Name>Auto</Name>
    <Description>blah-blah-blah</Description>
  </Category>
  <Category>
    <Id>2</Id>
    <Name>Moto</Name>
    <Description>bikes!</Description>
  </Category>
</Categories>

Upvotes: 0

Related Questions