1
<FileTransferSettings>
  <UploadPath src="user">C:\uploads</UploadPath>
  <DownloadPath src="app">C:\downloads</DownloadPath>
</FileTransferSettings>

我想将此 XML 反序列化为具有 2 个属性的 FileTransferSettings 对象 - UploadPath 和 DownloadPath。但我也想以src我的代码可以查询它的方式保留每个属性的属性。

我认为创建关联的 UploadPathSrc 和 DownloadPathSrc 属性有点尴尬和麻烦。

在 .NET 中是否有另一种表示方式?对我来说,该src属性似乎应该被视为元数据。对此有最佳做法吗?

(有关我为什么要这样做的背景 - 请参阅我之前的问题)。

谢谢。

4

3 回答 3

4

为了正确序列化和反序列化 XML,您需要使用 XML 序列化属性装饰类

[XmlRoot("FileTransferSettings")]
public class FileTransferSettings
{
   [XmlElement("DownloadPath")]
   public DownloadPath DownloadPath { get; set; }
   // ...
}

[XmlType("DownloadPath")]
public class DownloadPath
{ 
  [XmlAttribute]
  public string Src; // or use enum etc
  [XmlText]
  public string Text;
}

// the serialized XML looks like
<FileTransferSettings>
   <DownloadPath Src="...">text</DownloadPath>
   ....
</FileTransferSettings>
于 2009-02-23T17:22:44.300 回答
3

您可以创建第二个类 FileTransferPath,它有一个字符串值“Path”和一个枚举值“Source”

class FileTransferSettings
{
   public FileTransferPath UploadPath { get; set; }
   public FileTransferPath DownloadPath { get; set; }
   // ...
}

class FileTransferPath
{
   public string Path { get; set; }
   public FileTransferSource Source { get; set}

   public enum FileTransferSource
   {
     None,
     User,
     Application,
     // ...
   }
}

然后你可以使用类似的代码

   obj.UploadPath.Path;
   obj.UploadPath.Source;

您可以为类属性选择更好的名称;我不知道我喜欢Path的重复。 obj.Upload.Path或者更好的东西。

请注意,您无法使用 XmlSerialization 直接将其直接序列化/反序列化为您所拥有的格式;但它确实完成了你所需要的。(而且你仍然可以序列化为 XML,你只需要做更多的工作)

于 2009-02-23T17:08:43.850 回答
3

扩展 Daniel L. 的总体思路。

public Class FileTransferPath
{
  public Enum SourceEnum { User, App }

  public SourceEnum Source { get; set; }  //Automatic properties in 3.5 Syntax
  public string FilePath { get; set; }
}

public Class FileTransferSettings
{
  public FileTransferPath UploadPath { get; set; }
  public FileTransferPath DownLoadPath { get; set; }
}
于 2009-02-23T17:17:15.547 回答