前提・実現したいこと
C#でXMLの追記について教えてください。
試したこと
下記のようなXMLをクラスにしました。
XML
1<?xml version="1.0" encoding="utf-8"?> 2 <People xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> 3 <PeopleGroup> 4 <Person Name = "保坂" /> 5 <Person Name = "朝倉" /> 6 </PeopleGroup> 7 </People>
C#
1[System.SerializableAttribute()] 2[System.ComponentModel.DesignerCategoryAttribute("code")] 3[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://schemas.microsoft.com/developer/msbuild/2003")] 4[System.Xml.Serialization.XmlRootAttribute(Namespace = "http://schemas.microsoft.com/developer/msbuild/2003", IsNullable = false)] 5public partial class People 6{ 7 8 private PeoplePerson[] peopleGroupField; 9 10 [System.Xml.Serialization.XmlArrayItemAttribute("Person", IsNullable = false)] 11 public PeoplePerson[] PeopleGroup { 12 get { 13 return this.peopleGroupField; 14 } 15 set { 16 this.peopleGroupField = value; 17 } 18 } 19} 20 21[System.SerializableAttribute()] 22[System.ComponentModel.DesignerCategoryAttribute("code")] 23[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://schemas.microsoft.com/developer/msbuild/2003")] 24public partial class PeoplePerson 25{ 26 private string nameField; 27 28 [System.Xml.Serialization.XmlAttributeAttribute()] 29 public string Name { 30 get { 31 return this.nameField; 32 } 33 set { 34 this.nameField = value; 35 } 36 } 37}
http://takachan.hatenablog.com/entry/2017/06/22/225341
を参考に読み書きのコードを構築しました。
C#
1 public void AddFile(string filepath) 2 { 3 var people = Deserialize<People>(filepath); 4 5 //追加。 6 //XmlElement element = person.CreateElement("Name", "木村");//<=ここがうまくいかない。 7 8 //出力 9 Serialize(filepath people); 10 } 11 12 13 public static T Deserialize<T>(string loadPath) 14 { 15 using (var sr = new StreamReader(loadPath)) 16 { 17 return (T)new XmlSerializer(typeof(T)).Deserialize(sr); 18 } 19 } 20 21 public static void Serialize<T>(string savePath, T graph) 22 { 23 using (var sw = new StreamWriter(savePath, false, Encoding.UTF8)) 24 { 25 var ns = new XmlSerializerNamespaces(); 26 ns.Add(string.Empty, string.Empty); 27 28 new XmlSerializer(typeof(T)).Serialize(sw, graph, ns); 29 } 30 }
発生している問題・エラーメッセージ
読み書きはできると思うのですが、読んで追加することができません。
アドバイスお願いします。
補足情報(FW/ツールのバージョンなど)
Visual Studio 2017 Community
Windows 10 64bit
回答3件
あなたの回答
tips
プレビュー