Select a specific range of elements?
I want to select a specific range of elements within my XML files
Here is an example of the XML:
<urlset>
<url>
<loc>e1</loc>
<priority>1</priority>
</url>
<url>
<loc>e2</loc>
<priority>2</priority>
</url>
<url>
开发者_运维问答<loc>e3</loc>
<priority>1</priority>
</url>
<url>
<loc>e4</loc>
<priority>3</priority>
</url>
<url>
<loc>e4</loc>
<priority>1</priority>
</url>
<url>
<loc>e5</loc>
<priority>2</priority>
</url>
</urlset>
How to get the value of e2
to e4
?
var doc = XDocument.Parse(xml);
var result = doc.Element("urlset").Elements("url")
.SkipWhile(x => x.Element("loc").Value != "e2")
.TakeWhile(x => x.Element("loc").Value != "e4");
var result = urlset.Elements("url").Where(url =>
url.Element("loc").Value.ToString().CompareTo("e2") >= 0 &&
url.Element("loc").Value.ToString().CompareTo("e4") <= 0).Select(element => element.Element("loc").Value.ToString());
It uses standard (string) comparison - same as in alphabetical sorting, and it doesn't protect you against cases where some element would not have loc
subelement at all (null reference exception would be thrown).
You can use this XPath:
//url[loc = 'e2' or
(preceding-sibling::url/loc = 'e2' and following-sibling::url/loc = 'e4')
]
It will select url
with loc
= e2
, e3
, e4
an alternative way:
var urls = from url in doc.Descendants("urlset").Elements("url")
let str = Int32.Parse(url.Element("loc").Value.Replace("e",""))
where str >= 2 && str <= 4
select url;
or actually, a safer option that doesn't throw exceptions if loc is not in the form "e + integer value" (courtesy of Marc Gravell) would be:
int? TryParse(string s)
{
int i;
return int.TryParse(s, out i) ? (int?)i : (int?)null;
}
var urls = from url in doc.Descendants("urlset").Elements("url")
let str = TryParse(url.Element("loc").Value.Replace("e",""))
where str >= 2 && str <= 4
select url;
精彩评论