繁体   English   中英

从c#读取XML

[英]Read XML from c#

我正在尝试从ac#应用程序中读取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节点获取作业IdUprn ,并将值传递给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;
            }

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

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

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

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

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

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

这是经过测试的代码。 你需要命名空间。 请参阅下面的代码,它使用的是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();

        }
    }
}

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

我认为解决问题的最佳方法是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
    }

暂无
暂无

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

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