使用linq从站点地图文件中提取标题

时间:2012-08-18 02:52:01

标签: c# linq linq-to-xml

有没有办法使用XDocument和LINQ能够提取web.sitemap文件中所有title元素的所有siteMapNode属性,无论深度如何?任何如何做到这一点的例子将不胜感激!

3 个答案:

答案 0 :(得分:2)

你可以尝试这样的事情

XElement xelement = XElement.Load(Server.MapPath("~/web.sitemap"));
    var urlList = xelement.Descendants().Attributes()
       .Where(x => x.Name == "title")
       .Select(x => x.Value);

    foreach (string s in urlList)
    {

    }

答案 1 :(得分:0)

string sitemapfile = File.ReadAllText("path of web.sitemap");

XDocument doc = XDocument.Parse(sitemapfile);

var elements = doc.Root.Elements("siteMapNode");
foreach (var elem in elements) {
    if (elem.Attribute("title") != null)
         {
        //do your work
         }

答案 2 :(得分:0)

有时,使用普通的旧XPath要容易得多。

var doc = XDocument.Parse(contentsOfFile);
doc.XPathEvaluate("//@title");
foreach (var element in ((IEnumerable)result).Cast<XAttribute>())
{
    Console.WriteLine("{0} has value {1}", element.Name, element.Value);
}