我正在尝试使用子级decendent属性== value
捕获Elementsclass Program
{
static void Main(string[] args)
{
XDocument doc = XDocument.Load(@"path to doc");
var query = from q in doc.Elements("Candidates").Elements("Candidates")
//How to filter based on descendant attribute value
where (string)q.Descendants("CandidatesPropertyValue")
.Attributes["PropertyValue"] != "Consumer Sales & Information"
//? this doesn't work obviously
select q;
string type;
string val;
foreach (var record in query)
{
foreach (XAttribute a in record.Element("Candidates").Attributes())
{
Console.WriteLine("{0} = \"{1}\"", a.Name.ToString(), a.Value.ToString());
}
foreach (XElement e in record.Descendants())
{
type = (string)e.Attribute("PropertyType").Value;
val = (string)e.Attribute("PropertyValue").Value;
Console.WriteLine(" {0} = \"{1}\"", type, val);
}
}
Console.ReadLine();
}
<CandidatesRoot>
I WANT THIS ELEMENT
- <Candidates ...bunch of attributes...>
<CandidatesPropertyValue PropertyType="Type1" PropertyValue="Value1" />
<CandidatesPropertyValue PropertyType="Type2" PropertyValue="Value2" />
<CandidatesPropertyValue PropertyType="Type3" PropertyValue="Value3" />
<CandidatesPropertyValue PropertyType="Type4" PropertyValue="Value4" />
<CandidatesPropertyValue PropertyType="Type5" PropertyValue="Value5" />
</Candidates>
BUT I DON'T WANT THIS ONE
- <Candidates ...bunch of attributes...>
<CandidatesPropertyValue PropertyType="Type1" PropertyValue="Value1" />
<CandidatesPropertyValue PropertyType="LineOfBusiness" PropertyValue="Consumer Sales & Information" />
<CandidatesPropertyValue PropertyType="Type2" PropertyValue="Value2" />
<CandidatesPropertyValue PropertyType="Type3" PropertyValue="Value3" />
<CandidatesPropertyValue PropertyType="Type4" PropertyValue="Value4" />
<CandidatesPropertyValue PropertyType="Type5" PropertyValue="Value5" />
</Candidates>
答案 0 :(得分:2)
您可以使用XPath
using System.Xml.XPath;
...
String val = "\"Consumer Sales & Information\"";
String xpath = String.Format(".//CandidatesPropertyValue[@PropertyValue= {0}]", val);
doc.XPathSelectElements(xpath);
答案 1 :(得分:1)
我打算猜测并说你需要把它改成:
where (string)q.Descendants("CandidatesPropertyValue")
.Attributes("PropertyValue").SingleOrDefault()
如果它至少需要一个没有该值的后代:
where q.Descendants("CandidatesPropertyValue")
.Attributes("PropertyValue")
.Any(a => a.Value != "Consumer Sales & Information")
答案 2 :(得分:0)
这将查找名为Candidates
的所有元素,这些元素至少有一个名为CandidatesPropertyValue
的后代,其中至少有一个名为PropertyValue
的属性,其值为"Consumer Sales & Information"
:
var query = from q in doc.Elements("Candidates").Elements("Candidates")
where q.Descendants("CandidatesPropertyValue")
.Any(p => p.Attributes("PropertyValue")
.Any(a => a.Value == "Consumer Sales & Information"))
select q;