1

特定の XML ファイルを単一のオブジェクトにデシリアライズしていますが、これは正常に機能しています。ただし、別のオブジェクトに逆シリアル化する必要がある属性を追加するように XML ファイルを調整する必要があるため、1 つの指定された xml ファイルから 2 つのオブジェクトを設定できますが、これは 1 回の操作で可能ですか?

ここに私の現在のコードとXMLがあります:

XML 現在の状態:

<NameCollection>
   <Names>
      <Name>
        <description></description>
      <Name>
      <Name>
        <description></description>
      <Name>
   </Names>
</NameCollection>

XML 私が望むように:

<NameCollection>
  <GenericName></GenericName>
  <GenericDescription></GenericDescription>
   <Names>
      <Name>
        <description></description>
      <Name>
      <Name>
        <description></description>
      <Name>
   </Names>
</NameCollection>

コード:

NameCollection commands;

XMLSerializer serializer = new XMLSerializer(typeof(NameCollection));
StreamReader streamReader = new StreamReader(xmlpath);

commands = (NameCollection)serializer.Derserialize(streamreader);

streamReader.Close();

そして現在のオブジェクト:

[Serializable()]
public class TestCommand
{
   public string description{get;set;}
}

[Serializable()]
[XmlRoot("NameCollection")]
public class NameCollection
{
   [XmlArray("Commands")]
   [XmlArrayItem("Command", typeof(TestCommand))]
   public TestCommand[] TestCommand {get;set;}
}

次に、GenericName および GenericDescription 属性を別の別のオブジェクトに追加したいと考えています。

4

2 に答える 2

3

2 つのクラスではなく、XML の構造をクラスに反映させることが後になると思います。したがって、次のような構造が必要です。

public class TestCommand
{
   public string description{get;set;}
}

[XmlRoot("NameCollection")]
public class NameCollection
{
    public string GenericName {get; set;}
    public string GenericDescription {get; set;}

   [XmlArray("Commands")]
   [XmlArrayItem("Command", typeof(TestCommand))]
   public TestCommand[] TestCommand {get;set;}
}

次に、まったく同じ方法でシリアル化して、作業を完了します。

于 2012-10-02T13:22:49.527 に答える
2

あなたが持っているレイアウトでは、XmlSerializerこれらの追加の値を配置したい唯一の場所は on ですNameCollection

[XmlRoot("NameCollection")]
public class NameCollection
{
    public string GenericName {get;set:}
    public string GenericDescription {get;set:}

    [XmlArray("Names")]
    [XmlArrayItem("Name", typeof(TestCommand))]
    public TestCommand[] TestCommand {get;set;}
}

他のオブジェクトに移動したい場合は、それXmlSerializerを行うつもりはありません。

于 2012-10-02T13:23:04.253 に答える