[英]Store XML from SQL Server in object, and parse
I have a column in a SQL Server table of datatype XML that I need to read into my c# application and store into an object. 我在SQL Server表中有一个数据类型为XML的列,需要将其读入c#应用程序并将其存储到一个对象中。 The format of the data in the column is such 列中数据的格式如下
<call>
<attempted>
<enterdata/>
</attempted>
<completed>
<enterdata/>
<updatedate/>
</completed>
</call>
The idea is, the user calls a customer and afterwards must fill out a report. 想法是,用户致电客户,然后必须填写报告。 After indicating whether they reached the customer (completed) or not (attempted), the application will parse the XML accordingly and determine which updates it must make in the system. 在指示他们是否到达客户(完成)或未到达(尝试)之后,应用程序将相应地解析XML并确定它必须在系统中进行的更新。
However, I don't know which datatype to use inside my Call class to store this information, and then parse it later to see which updates need made. 但是,我不知道在Call类中使用哪种数据类型来存储此信息,然后稍后对其进行解析以查看需要进行哪些更新。 I tried using XElement
, but got an error saying "Cannot implicitly convert type 'object' to 'System.Xml.Linq.XElement'. I get a similar error when I cast it, but says to 'String' instead, I believe. I was hoping to get some advice on how to approach this, from what data type to store the XML data in, to how to parse it. 我尝试使用XElement
,但是收到一条错误消息:“无法将类型'object'隐式转换为'System.Xml.Linq.XElement'。我在投射时会遇到类似的错误,但我相信是对'String'说的。我希望从如何存储XML数据的数据类型到如何解析这方面获得一些建议。
Here is an solution: 这是一个解决方案:
"setting" is the xml saved in DB. “设置”是保存在数据库中的xml。
IDictionary<string, string> setting = new Dictionary<string, string>();
using (DbDataReader reader = command.ExecuteReader())
{
if (reader.Read())
{
object settingValue = reader["setting"];
if (settingValue != null)
{
try
{
// Test if the content can be parsed as XElement before contract deserialize
XElement xNode = XElement.Parse(settingValue.ToString());
if (xNode != null)
{
setting = (IDictionary<string, string>)XmlUtil.DataContractDeserialize(settingValue.ToString(), setting.GetType());
}
}
catch (XmlException)
{
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.