bate's blog

調べたこと実装したことなどを取りとめもなく書きます。

FormでXML入力

FormでXMLの内容を入力してXMLに保存的なことをした。
将来的にはパーティクルとかのデータを作成できるようにする予定。

出力したXML

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<!--パーティクルデータ-->
<Particle>
  <ParticleInfo>
    <Name Type="string">abc</Name>
  </ParticleInfo>
  <ParticleData>
    <Position Type="float">100.5</Position>
  </ParticleData>
</Particle>

コード

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.Windows.Forms;

namespace XMLForm
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button_save_Click(object sender, EventArgs e)
        {
            string particle_name = particle_name_mtb.Text;
            float particle_position = float.Parse(particle_position_mtb.Text);

            var xml_particle = new XDocument(new XDeclaration("1.0", "utf-8", "yes"));
            xml_particle.Add(new XComment("パーティクルデータ"));
            xml_particle.Add(new XElement("Particle"));

            // パーティクル情報
            XElement elem = new XElement("ParticleInfo");
            XElement sub_elem = new XElement("Name", particle_name);
            sub_elem.Add(new XAttribute("Type", "string"));
            elem.Add(sub_elem);
            xml_particle.Root.Add(elem);

            // パーティクルデータ
            elem = new XElement("ParticleData");
            sub_elem = new XElement("Position", particle_position);
            sub_elem.Add(new XAttribute("Type", "float"));
            elem.Add(sub_elem);
            xml_particle.Root.Add(elem);

            string xml_name = "D:/text/xml/";
            xml_name += particle_name + ".xml";
            xml_particle.Save(@xml_name);
        }
    }
}