【发布时间】:2012-06-30 00:44:25
【问题描述】:
假设您有一个 XML 文件:
<experiment
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="experiment.xsd">
<something />
<experiment>
你有 xsd 文件:
...
<xs:attribute name="hello" type="xs:boolean" use="optional" default="false" />
...
假设属性“hello”是“something”元素的可选属性,默认值设置为“false”。
使用XML LINQ的XDocument时,属性缺失,导致程序读取失败:
XDocument xml = XDocument.Load("file.xml");
bool b = bool.Parse(xml.Descendants("something").First().Attribute("hello").Value); // FAIL
LINQ 是自动加载 XML 架构(来自根元素“experiment”的“xsi:noNamespaceSchemaLocation”属性)还是我必须手动强制加载?
如何强制 LINQ 读取可选属性及其默认值?
【问题讨论】:
-
这就是为什么你应该使用强制转换而不是使用
Value属性(顺便返回一个字符串)。 -
我用的是 bool.Parse,只是忘了放在那里
标签: c# xml xml-parsing xsd linq-to-xml