XML元素属性值是否始终是字符串的数据类型? [英] Is XML Elements Attribute value always data type of string?

查看:422
本文介绍了XML元素属性值是否始终是字符串的数据类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我使用LINQ创建XML文档时,当我向具有某些属性的Root元素添加一些XElement时,以及当我使用LINQ读取该文档的XElement时,默认情况下,XAttributes.Value的返回值为字符串!
为了将此值分配给布尔类型的变量,必须调用函数"Convert.ToBoolean()"

When I create a XML Document using LINQ, when I add some XElement to Root element with some Attributes and when I read that document`s XElement using LINQ, the returned value of XAttributes.Value is string by default!
In order to assign this value to bool type of variable, it is necessary to call function "Convert.ToBoolean()"

  XDocument Xd = new XDocument(new XElement("Numbers"));
  Xd.Root.Add(new XElement("13", new XAttribute("Name", "13")
                               , new XAttribute("IsEvenNumber", false)
                               , new XAttribute("HowManyDevidersItHas", 2)));
  Xd.Save(@"C:\XDocument.xml");
  bool b1 = Convert.ToBoolean(XD1.Root.Element("13").Attribute("IsEvenNumber").Value);
  ...

如您所见:
XAttribute的名称为"Name"的值必须为长类型!
名为"IsEvenNumber"的XAttribute的值必须是布尔类型!

As you can see:
the value of XAttribute called "Name" must be as a long type!
the value of XAttribute called "IsEvenNumber" must be a bool type!

我需要知道:是否可以创建带有某些XAttributes的XElement,保存它,然后再次读取它,并将其XAttributes.Value分配给某些bool类型变量,而无需调用"Convert.ToBoolean()"函数?

I need to know: Is it possible to create an XElement with some XAttributes, save it, read it again and assign its XAttributes.Value to some bool type variable without calling " Convert.ToBoolean()" function?!

推荐答案

不幸的是,XElement.Value属性似乎是字符串.

Unfortunately not, the XElement.Value property appears to be a string.

http ://msdn.microsoft.com/zh-CN/library/system.xml.linq.xelement.value(v = vs.90).aspx

因此,您将始终必须将值转换为数据类型.

Thus you will always have to cast the value to your data type.

这篇关于XML元素属性值是否始终是字符串的数据类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆