将嵌套DataSet输出到xml

时间:2017-11-24 15:45:25

标签: c# xml asp.net-web-api

我正在尝试将嵌套数据集输出到xml,用于web api,但xml不正确

这是生成的xml

<ArrayOfDamages>
<Damages>
    <Id>1</Id>
    <Fk_LocationCodes_Id>11</Fk_LocationCodes_Id>
    <Fk_DamageCodes_Id>5</Fk_DamageCodes_Id>
    <Fk_SeverityCodes_Id>3</Fk_SeverityCodes_Id>
    <Fk_Inspections_Id>2</Fk_Inspections_Id>
    <isDeleted>false</isDeleted>
    <DamagePictures>
        <Fk_Damages_Id>1</Fk_Damages_Id>
        <Path>11331521400750-23112017-155252.jpg</Path>
        <isDeleted>false</isDeleted>
    </DamagePictures>
    <DamagePictures>
        <Fk_Damages_Id>1</Fk_Damages_Id>
        <Path>11331521400750-23112017-155252.jpg</Path>
        <isDeleted>false</isDeleted>
    </DamagePictures>
</Damages>
</ArrayOfDamages>

这是我的web api需要的xml

<ArrayOfDamages>
<Damages>
    <Id>1</Id>
    <Fk_LocationCodes_Id>11</Fk_LocationCodes_Id>
    <Fk_DamageCodes_Id>5</Fk_DamageCodes_Id>
    <Fk_SeverityCodes_Id>3</Fk_SeverityCodes_Id>
    <Fk_Inspections_Id>2</Fk_Inspections_Id>
    <isDeleted>false</isDeleted>
    <pictures>
        <DamagePictures>
            <Fk_Damages_Id>1</Fk_Damages_Id>
            <Path>11331521400750-23112017-155252.jpg</Path>
            <isDeleted>false</isDeleted>
        </DamagePictures>
        <DamagePictures>
            <Fk_Damages_Id>1</Fk_Damages_Id>
            <Path>11331521400750-23112017-155252.jpg</Path>
            <isDeleted>false</isDeleted>
        </DamagePictures>
    </pictures>
</Damages>
</ArrayOfDamages>

有什么办法吗?

由于

1 个答案:

答案 0 :(得分:0)

使用Xml Linq:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(FILENAME);

            XElement pictures = new XElement("pictures",doc.Descendants("DamagePictures"));

            for (int i = doc.Descendants("DamagePictures").Count() - 1; i >= 0; i--)
            {
                XElement damagePicture = doc.Descendants("DamagePictures").Skip(i).FirstOrDefault();
                if (i == 0)
                {
                    damagePicture.ReplaceWith(pictures);
                }
                else
                {
                    damagePicture.Remove();
                }
            }
        }
    }
}