Click here to Skip to main content
15,910,123 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hey guys,
I have xml looks like that:
XML
<Root>
  <Categories TopCategory="txt 1" MediumCategory="txt 2" SubCategory="txt 3" />
  <Categories TopCategory="txt 4" MediumCategory="txt 4" SubCategory="txt 5" />
  <Categories TopCategory="txt 7" MediumCategory="txt 8" SubCategory="txt 9" />
  <Categories TopCategory="txt 10" MediumCategory="txt 11" SubCategory="txt 12" />
  <Categories TopCategory="txt 13" MediumCategory="txt 14" SubCategory="txt 15" />
  <Categories TopCategory="txt 16" MediumCategory="txt 17" SubCategory="txt 18" />
</Root>


Now, the xml is passing to an XmlDocument object and what i want is extracting "TopCategory" & "MediumCategory" only where the value of "SubCategory" == "txt 12" (for example) using LINQ.
Any Ideas? please help....

What I have tried:

.......................................................
Posted
Updated 6-Mar-17 7:34am
v2

This website will show you how: LINQ To XML Tutorials with Examples | DotNetCurry[^] - see point 5. "How Do I access Specific Element having a Specific Attribute using LINQ to XML" - easy to adapt to your requirements
 
Share this answer
 
As an alternative to solution 1 by Graeme_Grant[^], i'd like to say...

MSDN documentation is very good. I'd suggest to start with:
LINQ to XML Overview (C#)[^]
LINQ to XML (C#)[^]
Basic Queries (LINQ to XML) (C#)[^], especially: How to: Find an Element with a Specific Attribute (C#)[^]

I'd resolve your issue this way:

C#
string xcontent = @"<Root>
  <Categories TopCategory='txt 1' MediumCategory='txt 2' SubCategory='txt 3' />
  <Categories TopCategory='txt 4' MediumCategory='txt 4' SubCategory='txt 5' />
  <Categories TopCategory='txt 7' MediumCategory='txt 8' SubCategory='txt 9' />
  <Categories TopCategory='txt 10' MediumCategory='txt 11' SubCategory='txt 12' />
  <Categories TopCategory='txt 13' MediumCategory='txt 14' SubCategory='txt 15' />
  <Categories TopCategory='txt 16' MediumCategory='txt 17' SubCategory='txt 18' />
</Root>";

XmlReader rdr = XmlReader.Create(new StringReader(xcontent));
XDocument xdoc = XDocument.Load(rdr);

var result = xdoc.Descendants()
		.Where(x=>(string)x.Attribute("SubCategory")=="txt 12");


Above code should return (IEnumerable<XElement>):
<Categories TopCategory="txt 10" MediumCategory="txt 11" SubCategory="txt 12" />
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900