XML.Linq - 根据另一个值获取值

Tre*_*iel 1 c# xml linq

我试图使用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>
Run Code Online (Sandbox Code Playgroud)

所以,例如,我想尝试获得应该<Boolean><CustomField>哪里<Name>等于的值"Scotsm_A_n_Authority_Good""true"

我尝试过以下方法:

var xmlAnswers = xe.Element("CustomFields").Element("CustomField").Element("Scotsm_A_n_Authority_Good");
Run Code Online (Sandbox Code Playgroud)

但我得到一个错误说:

The ' ' character, hexadecimal value 0x20, cannot be included in a name...
Run Code Online (Sandbox Code Playgroud)

有人可以帮忙吗?

Jon*_*eet 6

你现在正在寻找错误的东西.您应该查找具有指定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);
Run Code Online (Sandbox Code Playgroud)

这将为您提供所有匹配CustomField元素.然后,您可以使用以下内容获取Boolean值:

foreach (var answer in xmlAnswers)
{
    int id = (int) answer.Element("ID");
    bool value = (bool) answer.Element("Boolean");
    // Use them...
}
Run Code Online (Sandbox Code Playgroud)

(您当然可以在LINQ查询中提取ID和值...)