Choosing an XElement from an XDocument

I really didn’t want to ask for help, because I know that I will find out eventually, but I spent too much time if the document had parent tags or a better structure, that would be part of the cupcake. Unfortunately, I am uploading a document and I just cannot figure out how to get the data.

I tried several linq and foreach queries using XElement as an iterator. In any case, here is an example of the structure.

<ResultSet xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="urn:yahoo:srch" xsi:schemaLocation="urn:yahoo:srch http://api.search.yahoo.com/SiteExplorerService/V1/InlinkDataResponse.xsd" totalResultsAvailable="247930100" firstResultPosition="99" totalResultsReturned="100">
 <Result>
  <Title>Adobe - Adobe Reader</Title> 
  <Url>http://get.adobe.com/fr/reader/</Url> 
  <ClickUrl>http://get.adobe.com/fr/reader/</ClickUrl> 
  </Result>
 <Result>
  <Title>Religious Tolerance</Title> 
  <Url>http://www.religioustolerance.org/</Url> 
  <ClickUrl>http://www.religioustolerance.org/</ClickUrl> 
  </Result>
 <Result>
  <Title>Applications Internet riches (RIA) | Adobe Flash Player</Title> 
  <Url>http://www.adobe.com/fr/products/flashplayer/</Url> 
  <ClickUrl>http://www.adobe.com/fr/products/flashplayer/</ClickUrl> 
  </Result>
 <Result>
  <Title>photo management software | Adobe Photoshop Lightroom 3</Title> 
  <Url>http://www.adobe.com/products/photoshoplightroom/</Url> 
  <ClickUrl>http://www.adobe.com/products/photoshoplightroom/</ClickUrl> 
  </Result>
 <Result>
  <Title>Battle for Wesnoth</Title> 
  <Url>http://www.wesnoth.org/</Url> 
  <ClickUrl>http://www.wesnoth.org/</ClickUrl> 
  </Result>
</ResultSet>

Here is an example of the last snippet.

foreach (XElement ele in xDoc.Descendants("ResultSet").Elements("Result"))
                {
                    CollectedUris.Add(ele.Element("Url").Value);
                }
+5
source share
2 answers

You need to add XNamespace:

XNamespace ns = "urn:yahoo:srch";

var query = xDoc.Root.Descendants( ns + "Result" ).Elements( ns + "Url" )

foreach( XElement e in query )
{
    CollectedUris.Add( e.Value );
}

Edit :
LINQ solution for bonus points:

xDoc.Root.Descendants( ns + "Result" )
    .Elements( ns + "Url" )
    .Select( x => x.Value ).ToList()
    .ForEach( CollectedUris.Add );
+8
source

, <Url> . , . .

using System.Xml.Linq;

foreach (XElement ele in xDoc.Root.Descendants("Result").Descendants("Url")
{
    CollectedUris.Add(ele.Value);
}

Root , Descendants <Result>. Descendants <Result> node <Url> .

+2

All Articles