Serialization of Class’s in C# into an XML file

I want to serialize the class ‘kyerocontent’ but only it’s content (kyero and property classes), so on the XML file generated, it doesn’t appear “kyerocontent” as an element.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>public async Task<string> GenerateKyeroXml(UserModel user, List<ProductFields> properties)
{
// Initialize the list to hold individual XML strings for each property
List<string> kyeroList = new List<string>();
// Foreach to transform each property to XML
properties.ForEach(property =>
{
// Transform the property to XML
var propertyobject = new Kyero.property
{
id = property?.Id, //verificar?
reference = GetValueOrNull(property?.Code)?.ToString(),//property61(está sempre null?) ou será name/code?
currency = GetValueOrNull(property?.PurchasingCurrency),
date = GetValueOrNull(property.DateCreate?.ToString("yyyy-MM-dd HH:mm:ss")), //verificar
price = Convert.ToDecimal(GetValueFromDictionary(property.CustomFields, "property70")?.ToString().Split("|")[0]), //verificar o 160000|EUR
type = GetValueFromDictionary(property.CustomFields, "property60")?.ToString(),//verificar "house" "land" etc...
province = null, //Algarve
country = GetValueFromDictionary(property.CustomFields, "property302")?.ToString(),
price_freq = null, //verificar sale/rent/etc
town = GetValueFromDictionary(property.CustomFields, "property305")?.ToString(),
//status = GetValueFromDictionary(property.CustomFields, "property69")?.ToString(),
beds = ConvertToNullableInt(GetValueFromDictionary(property.CustomFields, "property75")),
baths = ConvertToNullableInt(GetValueFromDictionary(property.CustomFields, "property76")),
pool = ConvertYNTo01(GetValueFromDictionary(property.CustomFields, "property79").ToString()), //verificar?
//images = new List<Kyero.XMLImageUrl>
//{
// new Kyero.XMLImageUrl
// {
// ID = imageCounter,
// url =GetValueFromDictionary(property.CustomFields, "property303")?.ToString(),
// },
//},
energyrating = new EnergyRating
{
consumption = ConvertConsumption(GetValueFromDictionary(property.CustomFields, "property83")?.ToString()),
},
surfacearea = new SurfaceArea
{
built = ConvertToNullableInt(GetValueFromDictionary(property.CustomFields, "property77")),
plot = ConvertToNullableInt(GetValueFromDictionary(property.CustomFields, "property78")),
},
desc = new XMLDescList
{
PT = GetValueFromDictionary(property.CustomFields, "property307")?.ToString(),
EN = GetValueFromDictionary(property.CustomFields, "property308")?.ToString(),
FR = GetValueFromDictionary(property.CustomFields, "property309")?.ToString(),
DE = GetValueFromDictionary(property.CustomFields, "property310")?.ToString(),
NL = GetValueFromDictionary(property.CustomFields, "property311")?.ToString(),
SV = GetValueFromDictionary(property.CustomFields, "property312")?.ToString(),
RU = GetValueFromDictionary(property.CustomFields, "property313")?.ToString(),
},
features = new List<string>
{
GetValueFromDictionary(property.CustomFields, "property279")?.ToString(),
GetValueFromDictionary(property.CustomFields, "property280")?.ToString(),
GetValueFromDictionary(property.CustomFields, "property281")?.ToString(),
GetValueFromDictionary(property.CustomFields, "property282")?.ToString(),
GetValueFromDictionary(property.CustomFields, "property283")?.ToString(),
GetValueFromDictionary(property.CustomFields, "property284")?.ToString(),
GetValueFromDictionary(property.CustomFields, "property285")?.ToString(),
}
.Where(feature => feature != null)
.ToList(),
};
// Serialize the individual property to XML and add it to the list
string propertyString = SerializeToXml(property);
kyeroList.Add(propertyString);
});
var kyeroobject = new kyero
{
feed_version = "3",
};
string kyeroString = SerializeToXml(kyeroobject);
kyeroList.Insert(0, kyeroString);
// Join all the individual XML strings into one string
string combinedkyero = string.Join("n", kyeroList);
// Wrap the combined XML content within a root element
string kyeroWithRoot = $"<root>{"n" + combinedkyero}n</root>";
// Write the combined XML string to a file
string filePath = "KyeroXML.xml";
await File.WriteAllTextAsync(filePath, kyeroWithRoot);
// Return the file path
return filePath;
}
private string SerializeToXml<T>(T obj)
{
XmlSerializer serializer = new XmlSerializer(typeof(T));
using (MemoryStream ms = new MemoryStream())
{
XmlWriterSettings settings = new XmlWriterSettings
{
Indent = true,
OmitXmlDeclaration = true
};
// Create XmlWriter with settings
using (XmlWriter xmlWriter = XmlWriter.Create(ms, settings))
{
// Create XmlSerializerNamespaces and set it to null to avoid serializing namespaces
XmlSerializerNamespaces namespaces = null;
// Serialize the object
serializer.Serialize(xmlWriter, obj, namespaces);
}
// Convert the serialized data to string
return Encoding.UTF8.GetString(ms.ToArray());
}
}
</code>
<code>public async Task<string> GenerateKyeroXml(UserModel user, List<ProductFields> properties) { // Initialize the list to hold individual XML strings for each property List<string> kyeroList = new List<string>(); // Foreach to transform each property to XML properties.ForEach(property => { // Transform the property to XML var propertyobject = new Kyero.property { id = property?.Id, //verificar? reference = GetValueOrNull(property?.Code)?.ToString(),//property61(está sempre null?) ou será name/code? currency = GetValueOrNull(property?.PurchasingCurrency), date = GetValueOrNull(property.DateCreate?.ToString("yyyy-MM-dd HH:mm:ss")), //verificar price = Convert.ToDecimal(GetValueFromDictionary(property.CustomFields, "property70")?.ToString().Split("|")[0]), //verificar o 160000|EUR type = GetValueFromDictionary(property.CustomFields, "property60")?.ToString(),//verificar "house" "land" etc... province = null, //Algarve country = GetValueFromDictionary(property.CustomFields, "property302")?.ToString(), price_freq = null, //verificar sale/rent/etc town = GetValueFromDictionary(property.CustomFields, "property305")?.ToString(), //status = GetValueFromDictionary(property.CustomFields, "property69")?.ToString(), beds = ConvertToNullableInt(GetValueFromDictionary(property.CustomFields, "property75")), baths = ConvertToNullableInt(GetValueFromDictionary(property.CustomFields, "property76")), pool = ConvertYNTo01(GetValueFromDictionary(property.CustomFields, "property79").ToString()), //verificar? //images = new List<Kyero.XMLImageUrl> //{ // new Kyero.XMLImageUrl // { // ID = imageCounter, // url =GetValueFromDictionary(property.CustomFields, "property303")?.ToString(), // }, //}, energyrating = new EnergyRating { consumption = ConvertConsumption(GetValueFromDictionary(property.CustomFields, "property83")?.ToString()), }, surfacearea = new SurfaceArea { built = ConvertToNullableInt(GetValueFromDictionary(property.CustomFields, "property77")), plot = ConvertToNullableInt(GetValueFromDictionary(property.CustomFields, "property78")), }, desc = new XMLDescList { PT = GetValueFromDictionary(property.CustomFields, "property307")?.ToString(), EN = GetValueFromDictionary(property.CustomFields, "property308")?.ToString(), FR = GetValueFromDictionary(property.CustomFields, "property309")?.ToString(), DE = GetValueFromDictionary(property.CustomFields, "property310")?.ToString(), NL = GetValueFromDictionary(property.CustomFields, "property311")?.ToString(), SV = GetValueFromDictionary(property.CustomFields, "property312")?.ToString(), RU = GetValueFromDictionary(property.CustomFields, "property313")?.ToString(), }, features = new List<string> { GetValueFromDictionary(property.CustomFields, "property279")?.ToString(), GetValueFromDictionary(property.CustomFields, "property280")?.ToString(), GetValueFromDictionary(property.CustomFields, "property281")?.ToString(), GetValueFromDictionary(property.CustomFields, "property282")?.ToString(), GetValueFromDictionary(property.CustomFields, "property283")?.ToString(), GetValueFromDictionary(property.CustomFields, "property284")?.ToString(), GetValueFromDictionary(property.CustomFields, "property285")?.ToString(), } .Where(feature => feature != null) .ToList(), }; // Serialize the individual property to XML and add it to the list string propertyString = SerializeToXml(property); kyeroList.Add(propertyString); }); var kyeroobject = new kyero { feed_version = "3", }; string kyeroString = SerializeToXml(kyeroobject); kyeroList.Insert(0, kyeroString); // Join all the individual XML strings into one string string combinedkyero = string.Join("n", kyeroList); // Wrap the combined XML content within a root element string kyeroWithRoot = $"<root>{"n" + combinedkyero}n</root>"; // Write the combined XML string to a file string filePath = "KyeroXML.xml"; await File.WriteAllTextAsync(filePath, kyeroWithRoot); // Return the file path return filePath; } private string SerializeToXml<T>(T obj) { XmlSerializer serializer = new XmlSerializer(typeof(T)); using (MemoryStream ms = new MemoryStream()) { XmlWriterSettings settings = new XmlWriterSettings { Indent = true, OmitXmlDeclaration = true }; // Create XmlWriter with settings using (XmlWriter xmlWriter = XmlWriter.Create(ms, settings)) { // Create XmlSerializerNamespaces and set it to null to avoid serializing namespaces XmlSerializerNamespaces namespaces = null; // Serialize the object serializer.Serialize(xmlWriter, obj, namespaces); } // Convert the serialized data to string return Encoding.UTF8.GetString(ms.ToArray()); } } </code>
public async Task<string> GenerateKyeroXml(UserModel user, List<ProductFields> properties)
{
    // Initialize the list to hold individual XML strings for each property
    List<string> kyeroList = new List<string>();

    // Foreach to transform each property to XML
    properties.ForEach(property =>
    {
        // Transform the property to XML
        var propertyobject = new Kyero.property
        {
            id = property?.Id, //verificar?
            reference = GetValueOrNull(property?.Code)?.ToString(),//property61(está sempre null?) ou será name/code?
            currency = GetValueOrNull(property?.PurchasingCurrency),
            date = GetValueOrNull(property.DateCreate?.ToString("yyyy-MM-dd HH:mm:ss")), //verificar
            price = Convert.ToDecimal(GetValueFromDictionary(property.CustomFields, "property70")?.ToString().Split("|")[0]), //verificar o 160000|EUR
            type = GetValueFromDictionary(property.CustomFields, "property60")?.ToString(),//verificar "house" "land" etc...
            province = null, //Algarve
            country = GetValueFromDictionary(property.CustomFields, "property302")?.ToString(),
            price_freq = null, //verificar sale/rent/etc
            town = GetValueFromDictionary(property.CustomFields, "property305")?.ToString(),
            //status = GetValueFromDictionary(property.CustomFields, "property69")?.ToString(),
            beds = ConvertToNullableInt(GetValueFromDictionary(property.CustomFields, "property75")),
            baths = ConvertToNullableInt(GetValueFromDictionary(property.CustomFields, "property76")),
            pool = ConvertYNTo01(GetValueFromDictionary(property.CustomFields, "property79").ToString()), //verificar?
            //images = new List<Kyero.XMLImageUrl>
            //{
            //    new Kyero.XMLImageUrl
            //    {
            //        ID = imageCounter,
            //        url =GetValueFromDictionary(property.CustomFields, "property303")?.ToString(),
            //    },
            //},
            energyrating = new EnergyRating
            {
                consumption = ConvertConsumption(GetValueFromDictionary(property.CustomFields, "property83")?.ToString()),
            },
            surfacearea = new SurfaceArea
            {
                built = ConvertToNullableInt(GetValueFromDictionary(property.CustomFields, "property77")),
                plot = ConvertToNullableInt(GetValueFromDictionary(property.CustomFields, "property78")),
            },
            desc = new XMLDescList
            {
                PT = GetValueFromDictionary(property.CustomFields, "property307")?.ToString(),
                EN = GetValueFromDictionary(property.CustomFields, "property308")?.ToString(),
                FR = GetValueFromDictionary(property.CustomFields, "property309")?.ToString(),
                DE = GetValueFromDictionary(property.CustomFields, "property310")?.ToString(),
                NL = GetValueFromDictionary(property.CustomFields, "property311")?.ToString(),
                SV = GetValueFromDictionary(property.CustomFields, "property312")?.ToString(),
                RU = GetValueFromDictionary(property.CustomFields, "property313")?.ToString(),
            },
            features = new List<string>
        {
            GetValueFromDictionary(property.CustomFields, "property279")?.ToString(),
            GetValueFromDictionary(property.CustomFields, "property280")?.ToString(),
            GetValueFromDictionary(property.CustomFields, "property281")?.ToString(),
            GetValueFromDictionary(property.CustomFields, "property282")?.ToString(),
            GetValueFromDictionary(property.CustomFields, "property283")?.ToString(),
            GetValueFromDictionary(property.CustomFields, "property284")?.ToString(),
            GetValueFromDictionary(property.CustomFields, "property285")?.ToString(),
        }
            .Where(feature => feature != null)
            .ToList(),
        };

        // Serialize the individual property to XML and add it to the list
        string propertyString = SerializeToXml(property);
        kyeroList.Add(propertyString);
    });

    var kyeroobject = new kyero
    {
        feed_version = "3",
    };
    string kyeroString = SerializeToXml(kyeroobject);
    kyeroList.Insert(0, kyeroString);

    // Join all the individual XML strings into one string
    string combinedkyero = string.Join("n", kyeroList);

    // Wrap the combined XML content within a root element
    string kyeroWithRoot = $"<root>{"n" + combinedkyero}n</root>";

    // Write the combined XML string to a file
    string filePath = "KyeroXML.xml";
    await File.WriteAllTextAsync(filePath, kyeroWithRoot);

    // Return the file path
    return filePath;
}

private string SerializeToXml<T>(T obj)
{
    XmlSerializer serializer = new XmlSerializer(typeof(T));
    using (MemoryStream ms = new MemoryStream())
    {
        XmlWriterSettings settings = new XmlWriterSettings
        {
            Indent = true,
            OmitXmlDeclaration = true
        };

        // Create XmlWriter with settings
        using (XmlWriter xmlWriter = XmlWriter.Create(ms, settings))
        {
            // Create XmlSerializerNamespaces and set it to null to avoid serializing namespaces
            XmlSerializerNamespaces namespaces = null;

            // Serialize the object
            serializer.Serialize(xmlWriter, obj, namespaces);
        }

        // Convert the serialized data to string
        return Encoding.UTF8.GetString(ms.ToArray());
    }
}

This is my code. I want to return every strings that it finds me on a list, which in case is this ‘combinedkyero’ but without the ‘kyerocontent’.

New contributor

Bruno Dias is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật