(C#) オブジェクトをXML文字列にする
概要
ログ出力のためにオブジェクトをXML文字列化することが多かったので、それ用のクラスをつくった。
ログを汚さないために1行で出力するバージョン付き。置換すれば元のXML文字列に戻せるので、いざというときは解析に使える。
中身は単なるXMLシリアライズなので渡すクラスにはSerializableAttributeが必要。
つくったクラス
using System; using System.IO; using System.Xml.Serialization; namespace ObjectToXmlString { public static class XmlStringHelper { // XML文字列化 public static string ConvertToXmlStirng(object obj, bool throwException = false) { var xmlString = string.Empty; try { XmlSerializer serializer = new XmlSerializer(obj.GetType()); using (StringWriter writer = new StringWriter()) { serializer.Serialize(writer, obj); xmlString = writer.ToString(); } } catch { if (throwException) { throw; } } return xmlString; } // XML文字列化(1行) public static string ConvertToXmlStringAsOneLine(object obj, string newLineReplacingString, bool throwException = false) { var xmlString = string.Empty; try { xmlString = ConvertToXmlStirng(obj, throwException); xmlString = xmlString.Replace(Environment.NewLine, newLineReplacingString); } catch { if (throwException) { throw; } } return xmlString; } } }
おためしコード
using System; using System.Collections.Generic; namespace ObjectToXmlString { [Serializable] public class Box { public int Volume { get; set; } = 10; public string Name { get; set; } = "box a"; public List<string> Items { get; } = new List<string>() { "Apple", "Orange" }; } class Program { static void Main(string[] args) { Box boxA = new Box(); WriteResult("XML文字列", XmlStringHelper.ConvertToXmlStirng(boxA)); WriteResult("XML文字列(1行)", XmlStringHelper.ConvertToXmlStringAsOneLine(boxA, "#")); Console.ReadKey(); } static void WriteResult(string title, string result) { Console.WriteLine("----------------"); Console.WriteLine($"{title}"); Console.WriteLine("----------------"); Console.WriteLine($"{result}"); Console.WriteLine(); } } }
実行結果
---------------- XML文字列 ---------------- <?xml version="1.0" encoding="utf-16"?> <Box xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <Volume>10</Volume> <Name>box a</Name> <Items> <string>Apple</string> <string>Orange</string> </Items> </Box> ---------------- XML文字列(1行) ---------------- <?xml version="1.0" encoding="utf-16"?>#<Box xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"># <Volume>10</Volume># <Name>box a</Name># <Items># <string>Apple</string># <string>Orange</string># </Items>#</Box>