使用C#从XML文件中提取数据

时间:2012-01-10 13:08:33

标签: c# asp.net xml visual-studio

我的/ bin文件夹中有一些XML文件(使用vs2010)。我想从这个xml中提取一些数据(属性,元素值)。使用C#的最佳方法是什么?

我是否需要使用XMLTextReader,或者创建一个xmlDocument会更好......我很困惑......

5 个答案:

答案 0 :(得分:2)

答案 1 :(得分:1)

System.Xml og System.Linq.Xml

我会推荐Linq2Xml:http://msdn.microsoft.com/en-us/library/bb387098.aspx

这是一本很好的指南:http://www.hookedonlinq.com/LINQtoXML5MinuteOverview.ashx

答案 2 :(得分:0)

以下是查询XML文件的简单示例

public class Job
{
    public int Id { get; set; }

    public int CompanyId { get; set; }

    public string Title { get; set; }

    public string Description { get; set; }

    public int HoursPerWeek { get; set; }

}

XML文件片段:

<?xml version="1.0" encoding="utf-8"?>
<Jobs>
  <Job>
    <Id>1</Id>
    <CompanyId>2</CompanyId>
    <Description>Must be willing to relocate to Nebraska.</Description>
    <HoursPerWeek>90</HoursPerWeek>
    <JobStatus>1</JobStatus>
    <JobType>3</JobType>
    <Location>NY</Location>
    <Title>Application Engineer for Gooooogle Plus</Title>
  </Job>
  <Job>

从XML文件填充Job对象的类

public class XMLJobsDAL
{

    XDocument JobDoc
    {
        get { return XDocument.Load(System.Web.HttpContext.Current.Server.MapPath("~/App_Data/Job.xml")); }
    }


    public List<Job> GetJobs()
    {
        var results = from job in JobDoc.Descendants("Job")
                      select new Job
        {
            Id = (int)job.Element("Id"),
            CompanyId = (int)job.Element("CompanyId"),
            Description = (string)job.Element("Description"),
            HoursPerWeek = (int)job.Element("HoursPerWeek"),
            Title = (string) job.Element("Title")
        }
        return results.ToList();
    }

    public Job GetJob(int id)
    {
        var result = from job in JobDoc.Descendants("Job")
                      where (int)job.Element("Id") == id
                      select new Job
        {
            Id = (int)job.Element("Id"),
            CompanyId = (int)job.Element("CompanyId"),
            Description = (string)job.Element("Description"),
            HoursPerWeek = (int)job.Element("HoursPerWeek"),
            Title = (string) job.Element("Title")
        }
        return result.SingleOrDefault();
    }

}

答案 3 :(得分:0)

我建议您检查Serialization。以下是如何使用ek_ny XML Document将XML序列化/反序列化到对象的一个​​小例子:

using System.IO;
using System.Xml.Serialization;
[Serializable]
    public class Job
    {
        public Job() { }

        public int ID { get; set; }
        public int CompanyID { get; set; }
        public string Description { get; set; }
        public int HoursPerWeek { get; set; }
        public int JobStatus { get; set; }
        public int JobType { get; set; }
        public string Location { get; set; }
        public string Title { get; set; }

        public void SerializeToXML(string path) 
        {
            //creates a file
            FileStream fs = new FileStream(path, FileMode.Create);

            //now we create the serializer
            XmlSerializer xs = new XmlSerializer(typeof(Job));
            //serialize it to the file
            xs.Serialize(fs, this);
            //close the file
            fs.Close();
        }
        public static Job DeserializeToJob(string path) { 
            //open file
            FileStream fs = new FileStream(path, FileMode.Open);

            //create deserializer
            XmlSerializer xs = new XmlSerializer(typeof(Job));

            //Deserialize
            Job job = (Job)xs.Deserialize(fs);
            //close the file
            fs.Close();
            //return the deserialized job
            return job;
        }
    }

实现:

  class Program
    {
        static void Main(string[] args)
        {
            Job j = new Job();
            j.CompanyID = 2;
            j.ID = 1;
            j.Description = "Must be willing to relocate to Nebraska.";
            j.HoursPerWeek = 90;
            j.JobStatus = 1;
            j.JobType = 3;
            j.Location = "NY";
            j.Title = "Application Engineer for Gooooogle Plus";

            //Saving the object serialized.
            j.SerializeToXML("MyJob.xml");

            //deserialize the saved job into a new instance
            Job j2 = Job.DeserializeToJob("MyJob.xml");
        }
    }

通过这种方式,您可以在XML之间来回访问对象。这对我来说是最好的。我在这里看到的唯一缺点是,如果你的XML文档有很多属性,你将不得不做一个非常大的类。

http://support.microsoft.com/kb/815813

http://www.switchonthecode.com/tutorials/csharp-tutorial-xml-serialization

祝你好运!

答案 4 :(得分:0)

有一个很好的方法可以做到这一点。您可以使用    DataTable.ReadXml(string fileName) 它很容易处理一切。根据问题,它可能有用或不有用。 请注意,此方法无法从xml文件获取架构,您应自行向表中添加列。