如何在c#中将XElement转换为字符串?

时间:2011-05-13 13:49:45

标签: c# string casting linq-to-xml xelement

这是我的代码:

SqlConnection conn4 = new SqlConnection("Data Source=.\\sqlexpress;Initial Catalog=test_BdbCSSQL01;Persist Security Info=False;Integrated Security=SSPI;");
conn4.Open();

string sql = "SELECT * FROM ERROROfSIDESStagingOUT";
SqlDataAdapter da = new SqlDataAdapter(sql, conn4);
DataTable dt = new DataTable();
da.Fill(dt);
DataRow dr;
dr = dt.NewRow();
dt.Rows.Add(dr);

XDocument doc = XDocument.Load("XmlString.xml");
XNamespace ns = "https://uidataexchange.org/schemas";

var node = doc.Descendants(ns + "EmployerTPASeparationResponse");
var node2 = node.ElementAt(i);

        foreach (var param in node2.Elements())
        {

            try
            {
                if (dr[param.Name.LocalName].ToString() == "PriorIncidentOccurrence")
                {
                    var PriorIncidentDescendants = param.Descendants(ns + "PriorIncidentOccurrence");
                    dr["PriorIncidentID"] = PriorIncidentDescendants.ElementAt(0).Value;                                        
                }

                if (dr.Table.Columns.Contains(param.Name.LocalName))
                {
                    dr[param.Name.LocalName] = param.Value;
                }
            }
            catch (Exception ee)
            {
                //TODO: SendMail
                string asdf = ee.ToString();
            }
        }
        SqlCommandBuilder sb = new SqlCommandBuilder(da);
        da.Update(dt);

if (conn4 != null)
{
    conn4.Close();
}

我正在尝试将dr[param.Name.LocalName]转换为类型字符串。以下两种情况都不起作用。

(string)dr[param.Name.LocalName]
dr[param.Name.LocalName].ToString()

1 个答案:

答案 0 :(得分:0)

我猜,您在第一个dr[param.Name.LocalName]声明中为该键指定了值之前,正在调用if

你应该说出你收到的错误。我猜它与铸造无关......

您可以尝试检查调试器中param.Name.LocalName的值(或使用Debug.WriteLine打印),并确保这些值都是DataRow中的有效列名。< / p>