2017-02-16 35 views
0

如何将每个属性都作为XElement?输出每个属性为XElement

我基本上试图将IEnumerable对象转换为Web服务中的XML。

这是我想要转换为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(); 
     } 

编辑

类别分类定义(使用的EntityFramework 6代码优先)

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; } 

编辑2

折扣类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类定义

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; } 
} 
+0

您可以添加XML示例吗?谁应该持有最终结果(XElement名单)?猫? – KernelMode

+0

它需要创建一个包含所有类别和属性的XML字符串。 – Orion

回答

0

因此,你实际上需要XML字符串,最简单的方法将是简单的XML序列化。例如。如果你有以下几种:

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

系列化的样子

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

输出:

<?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> 
+0

我得到以下errir:“System.Web.Services.Protocols.SoapException:服务器无法处理请求---> System.InvalidOperationException:有反映类型'System.Collections.Generic.List”的错误这是从Web服务中调用。 – Orion

+0

@Orion是否可以为您的问题添加“Category”类定义? –

+0

@Serygey请参阅编辑。 – Orion

1

使用节点的OuterXml财产。它会返回到你想要的。

return Configuration.OuterXml; 
+1

'Select(c => new XElement(“Element”,c))'会给你类的名字而不是属性的值 –

+0

OP已经将'Configuration'定义为'XElement',所以上面应该可以工作。 –

+0

请考虑XElement的内容 –

0

这是我能想出的最佳解决方案。它的工作,所以要接受它作为我的答案。

// 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; 

     } 
    }