从.NET中的XML文件填充集合的最简单方法

时间:2009-08-26 15:18:26

标签: .net xml xml-serialization

我有以下XML文件:

<?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对象集合的最快方法是什么?我应该查看序列化器吗?

谢谢!

3 个答案:

答案 0 :(得分:3)

假设您打算像这样输入XML语法:

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

然后这段代码应该解析它。未经测试。

var doc = XDocument.Load("input.xml");
var x = from script in doc.Descendants("scripts").Descendants("script")
        select new {
            Name = script.Element("ScriptName").Value,
            Body = script.Element("ScriptBody").Value
        };

答案 1 :(得分:3)

使用.Net Serialization绝对是我的首选,在这种情况下,您可以将文件反序列化为对象。如果你拿xml(我编辑了一下):

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

然后创建一些代表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; }
}

然后,如果设置正确,您可以反序列化文件:

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

罗布

答案 2 :(得分:2)

    var document = XElement.Load(fileName);
    var collection = from elem in document.Elements("script")
                     select new DBScript(
                                  elem.Element("ScriptName").Value,
                                  elem.Element("ScriptBody").Value
                                );

将为你做的伎俩