【问题标题】:How would you represent this XML in an object?您将如何在对象中表示此 XML?
【发布时间】:2009-02-23 17:07:24
【问题描述】:
<FileTransferSettings>
  <UploadPath src="user">C:\uploads</UploadPath>
  <DownloadPath src="app">C:\downloads</DownloadPath>
</FileTransferSettings>

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

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

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

(有关为什么我正在尝试这样做的背景 - 请参阅我的previous question)。

谢谢。

【问题讨论】:

  • 关于您之前关于 src 属性的问题有答案。

标签: .net xml xml-serialization


【解决方案1】:

为了正确序列化和反序列化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>

【讨论】:

  • 很好,为 XML 序列化 +1
【解决方案2】:

你可以创建第二个类,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,你只需要多做一点工作)

【讨论】:

  • 我想我最终会采用这种方法。我看到的唯一问题是,如果一个部分有 20 个设置并且它们并不都适合 FileTransferPath,我最终可能会出现类爆炸。不过谢谢你,这会起作用的。
  • @vg1890:嗯,根据您的需要,您可以包含某种可序列化的等效字典(键/值对)来存储其他信息。
【解决方案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; }
}

【讨论】:

  • 你不需要公开 SourceEnum 类型吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多