0

如果这是重复的,我深表歉意,因为那里有很多类似的问题,但不是我想要的。

这是我写的:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Xml.Serialization;
using DeptDataAccess;

namespace Basware_Web_Service.Controllers
{
    public class DepartmentDataController : ApiController
    {
        public IEnumerable<Department> Get()
        {
            using (DeptDBEntities entities = new DeptDBEntities())
            {
                return entities.Departments.ToList();
            }
        }

这是生成的:

<ArrayOfDepartment xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/DeptDataAccess">
<Department>
<Company>TEST_CO</Company>
<ID>1</ID>
<Text_1>0</Text_1>
<Text_2>Sample_1</Text_2>
</Department>
<Department>
<Company>TEST_CO</Company>
<ID>2</ID>
<Text_1>1</Text_1>
<Text_2>Sample_2</Text_2>
</Department>
<!--Additional Department elements omitted-->
</ArrayOfDepartment>

我要做的是将根元素从 ArrayOfDeparment 替换为 Document Element,将循环元素从 Department 替换为 Item。

我尝试添加 XmlArrayItem、XmlRoot 但不断收到错误和/或继续看到 ArrayOf*

4

1 回答 1

0

对响应延迟表示歉意......我使用的数据来自 ADO.NET 连接到我的 SQL Server DB。我尝试序列化数组的尝试永远不会奏效,所以我最终创建了一个“ParsedDeptData”类来序列化和重新定义要传递的元素。

我解析的数据类最终看起来像这样:

using DeptDataAccess;
using System.Xml.Serialization;

namespace TempNamespace.DepartmentPClass
{
    [XmlType("DocumentElement")]

    public class Items : List<Item>
    {
        public Items()
        {

            using (DeptDBEntities entities = new DeptDBEntities())
            {
                foreach (Department entity in entities.Departments)
                {
                    Item item = new Item(entity);
                    this.Add(item);
                }
            }
        }
    }

    public class Item
    {
        public int ID { get; set; }
        public string Text_1 { get; set; }
        public string Text_2 { get; set; }
        public string Company { get; set; }

        public Item()
        {
            this.ID = 0;
            this.Text_1 = string.Empty;
            this.Text_2 = string.Empty;
            this.Company = string.Empty;
        }

        public Item(int id, string text_1, string text_2, string company)
        {
            this.ID = id;
            this.Text_1 = text_1;
            this.Text_2 = text_2;
            this.Company = company;
        }

        public Item(Department entity)
        {
            this.ID = entity.ID;
            this.Text_1 = entity.Text_1;
            this.Text_2 = entity.Text_2;
            this.Company = entity.Company;
        }
    }
}

然后我将控制器调整为:

namespace Basware_Web_Service.Controllers
{
    public class DepartmentDataController : ApiController
    {
        public DepartmentPClass.Items Get()
        {

            DepartmentPClass.Items items = new DepartmentPClass.Items();

            return items;
        }
    }
}

吸取的教训是,据我所知,您不能序列化方法,需要进一步向上调整。

于 2018-10-05T12:42:11.463 回答