从c#读取XML

时间:2017-07-18 08:24:52

标签: c# xml xml-parsing

我正在尝试从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>

我正在尝试从joblist节点获取作业ID Uprn ,并将值传递给Sql Server DB。我试过这个,但我无法得到这些值,

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

我非常感谢任何帮助。感谢

4 个答案:

答案 0 :(得分: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是节点,而不是节点属性。

答案 1 :(得分: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 :(得分:2)

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>"; } 是你的朋友:

    get<TResult>(
        object: any,
        path: StringRepresentable|StringRepresentable[],
        defaultValue?: TResult
    ): TResult;

答案 3 :(得分: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
    }