我正在尝试使用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");
< / p>
我尝试了以下内容:
The ' ' character, hexadecimal value 0x20, cannot be included in a name...
但我得到一个错误说:
From Date, To Date, Agent Name
有人可以帮忙吗?
答案 0 :(得分: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);
这将为您提供所有匹配的CustomField
元素。然后,您可以使用以下内容获取Boolean
值:
foreach (var answer in xmlAnswers)
{
int id = (int) answer.Element("ID");
bool value = (bool) answer.Element("Boolean");
// Use them...
}
(您当然可以在LINQ查询中提取ID和值...)
答案 1 :(得分:2)
这是一个xml linq解决方案
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication93
{
class Program
{
static void Main(string[] args)
{
string 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>" +
"</Lead>";
XDocument doc = XDocument.Parse(xml);
//to get all customField
var results = doc.Descendants("CustomField").Select(x => new
{
id = (int)x.Element("ID"),
name = (string)x.Element("Name"),
boolean = (Boolean)x.Element("Boolean")
}).ToList();
//to get specific
XElement Scotsm_A_n_Authority_Good = doc.Descendants("CustomField")
.Where(x => ((string)x.Element("Name") == "Scotsm_A_n_Authority_Good") && (Boolean)(x.Element("Boolean"))).FirstOrDefault();
}
}
}