我正在尝试使用Linq to XML从基于另一个值的xml中提取一个值。
这是我的xml
<Lead>
<ID>1189226</ID>
<Client>
<ID>8445254</ID>
<Name>City of Lincoln Council</Name>
</Client>
<Contact>
<ID>5747449</ID>
<Name>Fred Bloggs</Name>
</Contact>
<Owner>
<ID>36612</ID>
<Name>Joe Bloggs</Name>
</Owner>
<CustomFields>
<CustomField>
<ID>31961</ID>
<Name>Scotsm_A_n_Authority_Good</Name>
<Boolean>true</Boolean>
</CustomField>
<CustomField>
<ID>31963</ID>
<Name>Scotsma_N_Need Not Want</Name>
<Boolean>false</Boolean>
</CustomField>
</CustomFields>
因此,例如,我想尝试在
<Boolean>
中获取<CustomField>
的值,其中<Name>
等于"Scotsm_A_n_Authority_Good"
应为"true"
我尝试了以下方法:
var xmlAnswers = xe.Element("CustomFields").Element("CustomField").Element("Scotsm_A_n_Authority_Good");
但我得到一个错误,说:
The ' ' character, hexadecimal value 0x20, cannot be included in a name...
有人可以帮忙吗?
最佳答案
您目前正在寻找错误的事物。您应该在CustomField
元素中查找具有指定值的Name
元素:
string target = "Scotsm_A_n_Authority_Good"; // Or whatever
var xmlAnswers = xe.Element("CustomFields")
.Elements("CustomField")
.Where(cf => (string) cf.Element("Name") == target);
这将为您提供所有匹配的
CustomField
元素。然后,您可以使用以下内容获取Boolean
值:foreach (var answer in xmlAnswers)
{
int id = (int) answer.Element("ID");
bool value = (bool) answer.Element("Boolean");
// Use them...
}
(您当然可以在LINQ查询中提取ID和值...)
关于c# - XML.Linq-根据另一个值获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37271680/