1
米国のList of XMLをXMLにシリアライズしています。属性を持つ出力要素のほとんどの名前を制御できますが、ルートノードは常に「ArrayOfStates」と呼ばれています。これを変更する方法はありますか?リスト<object>を.NETでXMLにシリアル化するときにルートノードの名前を変更するにはどうすればよいですか?
コード:
public class Program
{
[XmlArray("States")]
public static List<State> States;
public static void Main(string[] args)
{
PopulateListOfStates();
var xml = new XmlSerializer(typeof(List<State>));
xml.Serialize(new XmlTextWriter(@"C:\output.xml",Encoding.Default), States);
}
}
public struct State
{
[XmlAttribute]
public string Name;
[XmlArray("Neighbours")]
[XmlArrayItem("Neighbour")]
public List<string> Neighbours;
}
出力:余談として
<?xml version="1.0" encoding="Windows-1252"?>
<ArrayOfState xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<State Name="AL">
<Neighbours>
<Neighbour>FL</Neighbour>
<Neighbour>GA</Neighbour>
<Neighbour>MS</Neighbour>
<Neighbour>TN</Neighbour>
</Neighbours>
</State>
<State Name="FL">
<Neighbours>
<Neighbour>AL</Neighbour>
<Neighbour>GA</Neighbour>
</Neighbours>
</State>
<State Name="GA">
<Neighbours>
<Neighbour>AL</Neighbour>
<Neighbour>FL</Neighbour>
<Neighbour>NC</Neighbour>
<Neighbour>SC</Neighbour>
<Neighbour>TN</Neighbour>
</Neighbours>
</State>
...
</ArrayOfState>
、これらの要素(すなわち<Neighbour name="XX"/>
)の属性として "隣接" 元素の含有量を有することも可能ですか?
この答えのようにラッパールートオブジェクトを作成します([適切に#のLINQ C XMLファイルを読む] https://stackoverflow.com/questions/40391131/read-xml-file-properly-c-sharp-linq/40391198#40391198)。または、[この回答](https://stackoverflow.com/questions/1624540/how-to-set-root-node-name-when-xmlserializing-an-array/1624569#1624569)に示すように、ルート要素名を上書きします。 )。しかし、2番目の答えを使用する場合は、[ここ](https://stackoverflow.com/questions/23897145/memory-leak-using-streamreader-and-xmlserializer/)で説明されているように、シリアライザを静的にキャッシュする必要があります。 – dbc