简体   繁体   English

ASP.NET WEB API 中的 xml 序列化

[英]xml serialization in ASP.NET WEB API

Im developing a web api in C#.我在 C# 中开发一个 web api。 The web api should return an xml like: web api 应该返回一个 xml,如:

<personDatas>
 <personData>
   <affdatalist>
     <object1> information </object1>
     <object2> information </object2>
     <object3> information </object3>
   </affdatalist>
   <anotherObject1> infooo </anotherObject1>
   <anotherObject2> infooo </anotherObject2>
 </personData>
</personDatas>

The xml can have 1 to many personData elements and the personData element can have 1 to many affdatalist elements. xml 可以有 1 到多个 personData 元素,而 personData 元素可以有 1 到多个 affdatalist 元素。

What would be the best practice to generate such an XML in a web api using C# 6?使用 C# 6 在 Web api 中生成这样的 XML 的最佳实践是什么?

Ive tried with XSD based on a schema definition.我已经尝试使用基于模式定义的 XSD。

Any help would be greatly appreciated.任何帮助将不胜感激。

You can use the Serialize method to generate this xml from the model it self.您可以使用 Serialize 方法从它自己的模型生成此 xml。

public string SerializeXml<T>(T config) 
        {
            XmlSerializer xsSubmit = new XmlSerializer(typeof(T));
            string xml = "";
            XmlWriterSettings settings = new XmlWriterSettings();
            settings.OmitXmlDeclaration = false;

            using (var sww = new StringWriter())
            {
                using (XmlWriter writer = XmlWriter.Create(sww, settings))
                {
                    xsSubmit.Serialize(writer, config);
                    xml = sww.ToString();
                }
            }

            return xml;
        }

This will return XML string , you need the model which is similar to your required XML.这将返回 XML 字符串,您需要与所需 XML 相似的模型。 This is what i have created as model from your XML that you can change as per your requiment.这是我从您的 XML 创建的模型,您可以根据您的要求进行更改。

 [XmlRoot(ElementName = "affdatalist")]
    public class Affdatalist
    {
        [XmlElement(ElementName = "object1")]
        public string Object1 { get; set; }
        [XmlElement(ElementName = "object2")]
        public string Object2 { get; set; }
        [XmlElement(ElementName = "object3")]
        public string Object3 { get; set; }
    }

    [XmlRoot(ElementName = "personData")]
    public class PersonData
    {
        [XmlElement(ElementName = "affdatalist")]
        public Affdatalist Affdatalist { get; set; }
        [XmlElement(ElementName = "anotherObject1")]
        public string AnotherObject1 { get; set; }
        [XmlElement(ElementName = "anotherObject2")]
        public string AnotherObject2 { get; set; }
    }

    [XmlRoot(ElementName = "personDatas")]
    public class PersonDatas
    {
        [XmlElement(ElementName = "personData")]
        public PersonData PersonData { get; set; }
    }

You can use as sample below您可以使用以下示例

PersonDatas data = new PersonDatas();
var xml = this.SerializeXml<PersonDatas>(data); // your model with data

If you want c# classes like this如果你想要这样的 c# 类

using System;
using System.Xml.Serialization;
using System.Collections.Generic;
namespace namespace
{

    public class AffData {

        public string Property1 { get; set; }
    }




    public class AnotherObject1 {

        public string Property1 { get; set; }
    }


    public class AnotherObject2 {

        public string Property1 { get; set; }
    }


    public class PersonData {

        public List<AffData> AffDataList { get; set; }

        public AnotherObject1 AnotherObject1 { get; set; }

        public AnotherObject2 AnotherObject2 { get; set; }
    }

The below xml will work if you serialize List如果您序列化 List,则以下 xml 将起作用

<ArrayOfPersonData>
 <PersonData>
   <ArrayOfAffData>
     <AffData> 
<Property1>info</Property1>
 </AffData>
     <AffData> <Property1>info</Property1></AffData>
     <AffData> <Property1>info</Property1> </AffData>
   </ArrayOfAffData>
   <anotherObject1> <Property1>info</Property1> </anotherObject1>
   <anotherObject2> <Property1>info</Property1> </anotherObject2>
 </PersonData>
</ArrayOfPersonData>

This is my sample after using what Sulay Shah said:这是我使用 Sulay Shah 所说的话后的示例:

PersonDatas data = new PersonDatas();
            for (int x = 0; x < 2; x++)
            {

                data.PersonData = new PersonData();
                for (int i = 0; i < 2; i++)
                {
                    Affdatalist affdata = new Affdatalist();
                    affdata.Object1 = "LALALALALLALA";
                    affdata.Object2 = "lqlqlqlqlqlqlql";
                    affdata.Object3 = "ililililililililililil";
                    data.PersonData.Affdatalist.Add(affdata);
                }

                data.PersonData.AnotherObject1 = "ali";
                data.PersonData.AnotherObject2 = "Nazar";

                data.personDataList.Add(data.PersonData);
            }
            var xml = this.SerializeXml<PersonDatas>(data);

            return xml;

The above generated below上面生成的下面

xml:<?xml version="1.0" encoding="utf-16"?>
<personDatas xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <personData>
        <affdatalist>
            <object1>LALALALALLALA</object1>
            <object2>lqlqlqlqlqlqlql</object2>
            <object3>ililililililililililil</object3>
        </affdatalist>
        <affdatalist>
            <object1>LALALALALLALA</object1>
            <object2>lqlqlqlqlqlqlql</object2>
            <object3>ililililililililililil</object3>
        </affdatalist>
        <anotherObject1>ali</anotherObject1>
        <anotherObject2>Nazar</anotherObject2>
    </personData>
    <personData>
        <affdatalist>
            <object1>LALALALALLALA</object1>
            <object2>lqlqlqlqlqlqlql</object2>
            <object3>ililililililililililil</object3>
        </affdatalist>
        <affdatalist>
            <object1>LALALALALLALA</object1>
            <object2>lqlqlqlqlqlqlql</object2>
            <object3>ililililililililililil</object3>
        </affdatalist>
        <anotherObject1>ali</anotherObject1>
        <anotherObject2>Nazar</anotherObject2>
    </personData>
    <PersonData>
        <affdatalist>
            <object1>LALALALALLALA</object1>
            <object2>lqlqlqlqlqlqlql</object2>
            <object3>ililililililililililil</object3>
        </affdatalist>
        <affdatalist>
            <object1>LALALALALLALA</object1>
            <object2>lqlqlqlqlqlqlql</object2>
            <object3>ililililililililililil</object3>
        </affdatalist>
        <anotherObject1>ali</anotherObject1>
        <anotherObject2>Nazar</anotherObject2>
    </PersonData>
</personDatas>
 public static string ConvertToXml(object payload, string rootElement, bool addPrefixSuffix)
    {
        string json = JsonConvert.SerializeObject(payload);
        string elementName = "DummyRoot";
        if (addPrefixSuffix)
        {
            string prefix = "{" + elementName + ":";
            string postfix = "}";
            json = string.Concat(prefix, json, postfix);
        }
        var payloadXml = JsonConvert.DeserializeXNode(json, rootElement)?.ToString();
        if (addPrefixSuffix)
        {
            payloadXml = payloadXml.ToString().Replace("<" + elementName + ">", string.Empty);
            payloadXml = payloadXml.ToString().Replace("</" + elementName + ">", string.Empty);
        }
        return Regex.Replace(payloadXml, @"\s+", String.Empty);
    }

Use the above function like ConvertToXml(requeststring, "", false)... Here second parameter empty will returns your expected result.使用上面的函数,如 ConvertToXml(requeststring, "", false)... 这里第二个参数 empty 将返回您的预期结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM