填充:在.NET的XML文件中收集的最简单方法

问题描述:

我有下面的XML文件:

I have the following XML file:

<?xml version="1.0" encoding="utf-8" ?>
<scripts>
  <ScriptName>
    <name>
        "My Name"
    </ScriptName>
    <ScriptBody>
        "body contents"
    </ScriptBody>
  </script>
</scripts>

和以下对象:

    public class DbScript
{
    #region Constructors
    public DbScript()
        : this(string.Empty, string.Empty)
    {
    }
    public DbScript(string name, string body)
    {
        ScriptName = name;
        ScriptBody = body;
    }
    #endregion
    #region Properties
    /// <summary>
    /// Script name
    /// </summary>
    public string ScriptName { get; set; }
    /// <summary>
    /// Script body
    /// </summary>
    public string ScriptBody { get; set; }
    #endregion
}

什么是从XML文件的内容填充DBScript对象的集合的最快方法?我应该考虑串行器?

What is the quickest way to populate the collection of DBScript object from the contents of the XML file? Should I look into serializers?

谢谢!

使用.NET序列化绝对是我的preference,你会在这种情况下,反序列化文件的对象。如果你把你的xml(这是我编辑了一下):

Using .Net Serialization is absolutely my preference, in this case you would deserialize the file to an object. If you take your xml (which I edited a bit):

<?xml version="1.0" encoding="utf-8" ?>
<scripts>
  <script>
    <ScriptName>
        "My Name"
    </ScriptName>
    <ScriptBody>
        "body contents"
    </ScriptBody>
  </script>
</scripts>

然后创建一些类重presents的XML:

Then you create some classes the represents the xml:

public class Scripts
{

  /// <summary>
  /// only allow xml serializer to create instances.
  /// </summary>
  private Scripts()
  {        
  }
  [XmlElement]
  public List<script> script{ get; set; }
}
public class script
{
  public script()
  {
  }

  [XmlElement]
  public string ScriptName { get; set; }

  [XmlElement]
  public string ScriptBody{ get; set; }
}

然后当是所有设置正确,你可以反序列化文件:

And then when that is all set up correctly you can deserialize the file:

string xmlFilePath = "THE_PATH_TO_THE_XML";
XmlSerializer xmlSerializer = new XmlSerializer(typeof(Scripts));
using (XmlReader xmlReader = XmlReader.Create(xmlFilePath))
{
    Scripts scripts = (Scripts)xmlSerializer.Deserialize(xmlReader);
}

XML序列化是非常强大的,检查出来的文档: HTTP:/ /msdn.microsoft.com/en-us/library/ms950721.aspx

Xml serialization is really powerful, check it out in the docs: http://msdn.microsoft.com/en-us/library/ms950721.aspx.

罗伯