如何从XML获取值并迭代存储在变量中

时间:2018-12-25 09:17:13

标签: c# xml

我的XML格式如下。

<TxLife>
  <Policy>
    <PolNumber>BB1062632</PolNumber>
    <FirstName>EWAN</FirstName>
    <LastName>MCKENZIE</LastName>
    <BirthDate>1972-03-08</BirthDate>
    <MailType>ABC</MailType>
  </Policy>
  <Policy>
    <PolNumber>BB1234567</PolNumber>
    <FirstName>TEST</FirstName>
    <LastName>ONE</LastName>
    <BirthDate>1972-03-08</BirthDate>
    <MailType>DEF</MailType>
 </Policy>
</TxLife>

我已经编写了使用以下代码在字符串数组中获取值的代码:

 string[] arr = doc.Descendants("PolNumber").Select(element => element.Value).ToArray();

但不确定如何获取单个值并将其存储在变量中

2 个答案:

答案 0 :(得分:0)

选项1:反序列化

代替使用Linq To XML,您可以反序列化对象并存储值。

var serializer = new XmlSerializer(typeof(TxLife));
using (TextReader reader = new StringReader(strXml))
{
    var result = (TxLife)serializer.Deserialize(reader);
}

TxLife定义为

[XmlRoot(ElementName="Policy")]
public class Policy 
{
    [XmlElement(ElementName="PolNumber")]
    public string PolNumber { get; set; }
    [XmlElement(ElementName="FirstName")]
    public string FirstName { get; set; }
    [XmlElement(ElementName="LastName")]
    public string LastName { get; set; }
    [XmlElement(ElementName="BirthDate")]
    public string BirthDate { get; set; }
    [XmlElement(ElementName="MailType")]
    public string MailType { get; set; }
}

[XmlRoot(ElementName="TxLife")]
public class TxLife {
    [XmlElement(ElementName="Policy")]
    public List<Policy> Policy { get; set; }
}

选项2:Linq To Xml

如果您想坚持使用Linq To Xml,可以使用

var root = XElement.Parse(strXml);
var policies = new List<Policy>();
foreach(var item in root.Descendants("Policy"))
{
    policies.Add(new Policy
    {
     PolNumber= item.Element("PolNumber").Value,
     FirstName = item.Element("FirstName").Value,
     LastName = item.Element("LastName").Value,
     BirthDate = item.Element("BirthDate").Value,
      MailType = item.Element("MailType").Value
    });
}

答案 1 :(得分:0)

与其将Anu解决方案与for循环一起使用,不如将linq与select一起使用,这会更有效率。当元素不存在时,值也会引起问题,因此将其强制转换为字符串更好。参见下面的代码

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

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            string connStr = "Enter your connection string here";
            SqlConnection conn = new SqlConnection(connStr);
            conn.Open();

            SqlCommand cmd = new SqlCommand();
            cmd.CommandType = System.Data.CommandType.StoredProcedure;
            cmd.CommandText = "WB_SetNotification";  //stored procdure name

            SqlParameter policyNumber = cmd.Parameters.Add(new SqlParameter("@PolicyNumber", SqlDbType.VarChar, 20));
            cmd.Parameters.Add(policyNumber);
            cmd.Parameters["@PolicyNumber"].Direction = ParameterDirection.Input;

            SqlParameter firstName = cmd.Parameters.Add(new SqlParameter("@FirstName", SqlDbType.VarChar, 50));
            cmd.Parameters.Add(firstName);
            cmd.Parameters["@FirstName"].Direction = ParameterDirection.Input;

             SqlParameter lastName = cmd.Parameters.Add(new SqlParameter("@LastName", SqlDbType.VarChar, 50));
            cmd.Parameters.Add(lastName);
            cmd.Parameters["@LastName"].Direction = ParameterDirection.Input;

            SqlParameter dob = cmd.Parameters.Add(new SqlParameter("@DateOfBirth", SqlDbType.DateTime));
            cmd.Parameters.Add(dob);
            cmd.Parameters["@DateOfBirth"].Direction = ParameterDirection.Input;

            XDocument doc = XDocument.Load(FILENAME);

            List<Policy> policies = doc.Descendants("Policy").Select(item => new Policy()
            {
                PolNumber = (string)item.Element("PolNumber"),
                FirstName = (string)item.Element("FirstName"),
                LastName = (string)item.Element("LastName"),
                BirthDate = (string)item.Element("BirthDate"),
                MailType = (string)item.Element("MailType")
            }).ToList();

            foreach (Policy policy in policies)
            {
                cmd.Parameters["@PolicyNumber"].Value  = policy.PolNumber;
                cmd.Parameters["@FirstName"].Value = policy.FirstName;
                cmd.Parameters["@LastName"].Value = policy.LastName;
                cmd.Parameters["@DateOfBirth"].Value = policy.BirthDate;

                cmd.ExecuteNonQuery();
            }


        }
        public class Policy
        {
            public string PolNumber { get; set; }
            public string FirstName { get; set; }
            public string LastName { get; set; }
            public string BirthDate { get; set; }
            public string MailType { get; set; }
        }
    }
}