【发布时间】:2016-05-21 02:03:22
【问题描述】:
我有一些看起来像这样的 xml:
<forms>
<form name="admin" title="Admin Info">
<field name="primary" label="Primary Name" required="false">
<group desc="General" name="personalinfo" required="false" hide="false">
<field label="Photos" name="photoupload" required="false" hide="false">
<field label="First Name" name="firstanme" required="false" hide="false">
</group>
</form>
<form name = "..." etc>
....etc...
</form>
</forms>
我正在尝试从内部“字段”标签中获取信息。例如,我想在 name="photoupload" 时获取“required”和“hide”值。
到目前为止我所拥有的:
XDocument doc = XDocument.Parse(xmlTemplate);
var photoInfo = doc.Descendants("field")
.Where(field => field.Attribute("name").Value == "photoupload")
.Select(field => new
{
Hide = field.Attribute("hide").Value,
Required = field.Attribute("required").Value
})
.Single();
photoInfoTextBox.Text = photoInfo.Hide.ToString();
但是,我收到“Object reference not set to an instance of an object.”错误。我的猜测是代码试图从第一个“字段”标签(其中 name="primary")中获取信息,但实际上我想要来自内部字段标签的信息,特别是:
forms/form(where name="admin")/group(where desc="general")/field(where name="photoupload")。
我该怎么做呢?
【问题讨论】:
标签: c# xml linq-to-xml