从C#读取XML

3

我正在尝试从C#应用程序读取XML文件,但到目前为止都没有成功。这是XML文件:

<?xml version="1.0" encoding="utf-8"?>
<ExportJobs xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <JobList>
    <Job Id="555555">
      <Comments></Comments>
      <DueDate>2017-11-17</DueDate>
      <FormattedDueDate>17-Nov-2017 12:00</FormattedDueDate>
      <TargetDueDate>2017-11-17</TargetDueDate>
      <ServiceTypeId>3</ServiceTypeId>
      <ServiceType>Service</ServiceType>
      <TenantName>Miss Ash</TenantName>
      <Uprn>testUpr</Uprn>
      <HouseName></HouseName>
    </Job>
    <Job Id="666666">
      <Comments></Comments>
      <DueDate>2018-03-15</DueDate>
      <FormattedDueDate>15-Mar-2018 12:00</FormattedDueDate>
      <TargetDueDate>2018-03-15</TargetDueDate>
      <ServiceTypeId>3</ServiceTypeId>
      <ServiceType>Service</ServiceType>
      <TenantName>Mr Howard</TenantName>
      <Uprn>testUpr2</Uprn>
    </Job>
  </JobList>
</ExportJobs>

我正在尝试从工作列表节点中获取工作编号Uprn,并将这些值传递到Sql Server数据库。我尝试了以下代码,但无法获取这些值:

            string costCode;
            string uprn;

            //File path where the xml is located
            string filepath = "C:\\ExportJobs.xml";

            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(filepath);

            foreach (XmlNode node in xmlDoc.DocumentElement.ChildNodes)
            {

                costCode = node.Attributes["Id"].InnerText;
                uprn = node.Attributes["Uprn"].InnerText;
            }

非常感谢您的帮助。谢谢!


1
Uprn是一个元素,而不是属性;然而,在这里,XmlSerializer是你的好朋友... - Marc Gravell
4个回答

5

XmlSerializer 是您的好朋友:

using System;
using System.Collections.Generic;
using System.IO;
using System.Xml.Serialization;

public class ExportJobs
{
    public List<Job> JobList { get; } = new List<Job>();
}
public class Job
{
    [XmlAttribute]
    public int Id { get; set; }
    public string Comments { get; set; }
    public DateTime DueDate { get; set; }
    public string FormattedDueDate { get; set; }
    public DateTime TargetDueDate{ get; set; }
    public int ServiceTypeId { get; set; }
    public string ServiceType { get; set; }
    public string TenantName { get; set; }
    public string Uprn { get; set; }
    public string HouseName { get; set; }
}
static class P
{

    static void Main()
    {
        var ser = new XmlSerializer(typeof(ExportJobs));
        ExportJobs jobs;
        using (var sr = new StringReader(xml))
        {
            jobs = (ExportJobs) ser.Deserialize(sr);
        }

        foreach(var job in jobs.JobList)
        {
            Console.WriteLine($"{job.Id} / {job.Uprn}: {job.DueDate}");
        }  
    }

    const string xml = @"<?xml version=""1.0"" encoding=""utf-8""?>
<ExportJobs xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">
  <JobList>
    <Job Id=""555555"">
      <Comments></Comments>
      <DueDate>2017-11-17</DueDate>
      <FormattedDueDate>17-Nov-2017 12:00</FormattedDueDate>
      <TargetDueDate>2017-11-17</TargetDueDate>
      <ServiceTypeId>3</ServiceTypeId>
      <ServiceType>Service</ServiceType>
      <TenantName>Miss Ash</TenantName>
      <Uprn>testUpr</Uprn>
      <HouseName></HouseName>
    </Job>
    <Job Id=""666666"">
      <Comments></Comments>
      <DueDate>2018-03-15</DueDate>
      <FormattedDueDate>15-Mar-2018 12:00</FormattedDueDate>
      <TargetDueDate>2018-03-15</TargetDueDate>
      <ServiceTypeId>3</ServiceTypeId>
      <ServiceType>Service</ServiceType>
      <TenantName>Mr Howard</TenantName>
      <Uprn>testUpr2</Uprn>
    </Job>
  </JobList>
</ExportJobs>";
}

1
顺便提一下:在Visual Studio中确实有一个“编辑”=>“特殊粘贴”=>“将XML粘贴为类”的菜单选项,但如果您使用它,您会发现为什么我通常不使用它...(将生成的代码与上面答案中的代码进行比较) - Marc Gravell
非常感谢。我会测试这个。 - KMR

3

您正在访问根元素的ChildNodes,该元素仅包含Jobs元素,而该元素按顺序不包含属性IdUprn

通常做法是使用以下XPath查询:

foreach (XmlNode node in xmlDoc.DocumentElement.SelectNodes("Jobs/Job"))
{

    costCode = node.Attributes["Id"].InnerText;
    uprn = node.SelectSingleNode("Uprn").InnerText;
}

请注意,Uprn是节点而不是节点属性。

然而,Marc Gravell♦的答案更加贴切 :) - Mikhail Tulubaev

3

这是经过测试的代码。你需要引用命名空间。请看下面使用xml linq的示例代码。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication67
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(FILENAME);
            XElement exportJobs = doc.Root;
            XNamespace ns = exportJobs.GetDefaultNamespace();

            var results = exportJobs.Descendants(ns + "Job").Select(x => new {
                id = (string)x.Attribute(ns + "Id"),
                comment = (string)x.Element(ns + "Comments"),
                dueDate = (DateTime)x.Element(ns + "DueDate"),
                formattedDueDate = (DateTime)x.Element(ns + "FormattedDueDate"),
                targetDueDate = (DateTime)x.Element(ns + "TargetDueDate"),
                serviceTypeId = (int)x.Element(ns + "ServiceTypeId"),
                serviceType = (string)x.Element(ns + "ServiceType"),
                tenantName = (string)x.Element(ns + "TenantName"),
                uprn = (string)x.Element(ns + "Uprn"),
                houseName = (string)x.Element(ns + "HouseName")
            }).ToList();

        }
    }
}

2
我认为解决你的问题最好的方式是使用XDocument类。
    XDocument xDoc = XDocument.Load(@"D:\1.xml");
    foreach(var node in xDoc.Descendants("Job"))
    {
        id = node.Attribute("Id");
        foreach(var subnode in node.Descendants("Uprn"))
        {
            uprn = subnode.Value;
        }

        //or like that. but check it for null before
        uprn = node.Descendants("Uprn")?.First().Value
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接