我想在XML文件中选择特定范围的元素
以下是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>
如何将e2
的值设为e4
?
答案 0 :(得分:2)
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());
它使用标准(字符串)比较 - 与字母排序相同,并且它不会保护您免受某些元素根本不具有loc
子元素的情况(将抛出空引用异常)。 / p>
答案 1 :(得分:2)
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");
答案 2 :(得分:1)
另一种方式:
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;
或实际上,如果loc不是“e +整数值”(courtesy of Marc Gravell)形式,则不会抛出异常的更安全的选项是:
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;
答案 3 :(得分:1)
您可以使用此XPath:
//url[loc = 'e2' or
(preceding-sibling::url/loc = 'e2' and following-sibling::url/loc = 'e4')
]
它会选择url
loc
= e2
,e3
,e4