简体   繁体   English

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

[英]Extracting Data From XML File Using C#

I have some XML file sitting in my /bin folder (using vs2010). 我的/ bin文件夹中有一些XML文件(使用vs2010)。 I would like to extract some data (attributes, element values) from this xml. 我想从此xml中提取一些数据(属性,元素值)。 What is the best way to do this using C#? 使用C#做到这一点的最佳方法是什么?

do I need to use XMLTextReader or would it be better to create an xmlDocument...I'm confused... 我需要使用XMLTextReader还是创建xmlDocument会更好...我很困惑...

Either System.Xml og System.Linq.Xml System.Xml System.Linq.Xml

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

This is a good guide: http://www.hookedonlinq.com/LINQtoXML5MinuteOverview.ashx 这是一个很好的指南: http//www.hookedonlinq.com/LINQtoXML5MinuteOverview.ashx

Here is a simple example of querying an XML File 以下是查询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; }

}

Snippet of XML File: 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>

Class which populates Job objects from XML File 从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();
    }

}

I would recommend that you check Serialization out. 我建议您检查Serialization Here is a little example of how to Serialize/Deserialize XML to/from an object using ek_ny XML Document: 这是一个小示例,说明如何使用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;
        }
    }

Implementation: 执行:

  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");
        }
    }

With this you will get the object back and forth from and to XML. 有了这个,您将从XML中获取对象的来回。 This is what has worked the best for me. 这对我来说是最好的。 The only cons I can see here is that if your XML document has a lot of properties you will have to make a very big class. 我在这里只能看到的缺点是,如果您的XML文档具有很多属性,则必须创建一个非常大的类。

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

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

Good luck! 祝好运!

There's one good way to do this. 有一个好方法可以做到这一点。 You can use DataTable.ReadXml(string fileName) it takes care of everything easily. 您可以使用DataTable.ReadXml(string fileName)轻松处理所有事情。 Depending on the problem, it could be useful or not. 根据问题,它可能有用或无效。 Note this methods cannot get the schema from xml file, you should add columns to the table yourself. 请注意,此方法无法从xml文件获取架构,您应该自己向表中添加列。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM