T
T
TheTalion2017-11-11 16:01:23
C++ / C#
TheTalion, 2017-11-11 16:01:23

How to make the same structure in XML?

5a06f424ba4c1170334744.jpeg
Interested in how to write these fields from the code? when I try to just make a class, then all the fields are written inside, but how to add the fields like this, as in the picture, so that they are placed in the class name (like techtree version = "5"? Maybe these are attributes or what?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
mshak, 2017-11-11
@TheTalion

using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

namespace XmlSerializeDemo
{
    [XmlRoot("TechTree")]
    public class TechCollection
    {
        [XmlAttribute("version")]
        public int Version { get; set; }

        [XmlElement("Tech")]
        public TechItem Item { get; set; }
    }

    public class TechItem
    {
        [XmlAttribute("type")]
        public string Type { get; set; }

        [XmlAttribute("name")]
        public string Name { get; set; }
    }

    internal class Program
    {
        private static void Main(string[] args)
        {
            var e = new TechItem() { Type = "Noraml", Name = "Age 1" };
            var t = new TechCollection() { Version = 5, Item = e };

            Serialize(@".\demo.xml", t);
        }

        private static void Serialize<T>(string path, T obj)
        {
            XmlSerializer serializer = new XmlSerializer(obj.GetType());
            XmlWriterSettings settings = new XmlWriterSettings();
            settings.ConformanceLevel = ConformanceLevel.Document;
            settings.OmitXmlDeclaration = false; // не подавлять xml заголовок
            settings.Encoding = Encoding.UTF8; // кодировка
            settings.Indent = true; // добавлять отступы
            settings.IndentChars = "    "; // сиволы отступа

            // подавляем неймспейсы
            XmlSerializerNamespaces dummyNSs = new XmlSerializerNamespaces();
            dummyNSs.Add(string.Empty, string.Empty);

            using (FileStream fileStream = new FileStream(path, FileMode.Create))
            {
                using (XmlWriter xw = XmlWriter.Create(fileStream, settings))
                {
                    serializer.Serialize(xw, obj, dummyNSs);
                }
            }
        }
    }
}

at the exit
<?xml version="1.0" encoding="utf-8"?>
<TechTree version="5">
    <Tech type="Noraml" name="Age 1" />
</TechTree>

W
wcoder, 2017-11-11
@wcoder

Write as attributes:
XML attributes

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question