■101348 / inTopicNo.3) |
Re[2]: xmlファイルへコメント出力する方法 |
□投稿者/ ぼーちゃん (40回)-(2023/02/08(Wed) 09:20:24)
|
以下のような方法はあります。デシリアライズも問題ないです。
https://stackoverflow.com/questions/7385921/how-to-write-a-comment-to-an-xml-file-when-using-the-xmlserializer
対象クラスに余計なパブリックメンバを定義することになるので、あまりシンプルではないですが・・・
using System;
using System.Windows.Forms;
using System.Reflection;
using System.Xml;
using System.Xml.Serialization;
using System.Runtime.CompilerServices;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
var fileName = @"test.xml";
var obj = new SampleClass() { Number = 123, Message = "メッセージ1"};
XmlSerializer serializer = new XmlSerializer(typeof(SampleClass));
using(var sw = new System.IO.StreamWriter(fileName, false, new System.Text.UTF8Encoding(false)))
{
serializer.Serialize(sw, obj);
}
}
}
public class SampleClass
{
public int Number { get; set; }
[XmlAnyElement("MessageXmlComment")]
public XmlComment MessageXmlComment { get { return GetType().GetXmlComment(); } set { } }
[XmlComment("Messageのコメント")]
public string Message { get; set; }
}
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public class XmlCommentAttribute : Attribute
{
public XmlCommentAttribute(string value)
{
this.Value = value;
}
public string Value { get; set; }
}
public static class XmlCommentExtensions
{
const string XmlCommentPropertyPostfix = "XmlComment";
static XmlCommentAttribute GetXmlCommentAttribute(this Type type, string memberName)
{
var member = type.GetProperty(memberName);
if (member == null)
return null;
var attr = member.GetCustomAttribute<XmlCommentAttribute>();
return attr;
}
public static XmlComment GetXmlComment(this Type type, [CallerMemberName] string memberName = "")
{
var attr = GetXmlCommentAttribute(type, memberName);
if (attr == null)
{
if (memberName.EndsWith(XmlCommentPropertyPostfix))
attr = GetXmlCommentAttribute(
type, memberName.Substring(0, memberName.Length - XmlCommentPropertyPostfix.Length)
);
}
if (attr == null || string.IsNullOrEmpty(attr.Value))
return null;
return new XmlDocument().CreateComment(attr.Value);
}
}
}
|
|