2010-05-11 6 views
3

내가 만든 Google Sitemap에 속성이 채워진 urlset 요소가 있지만 아무런 속성이 없으면 작동하지 않는 Linq-2-XML 쿼리가 있습니다. 선물.XML에 Linq을 사용하여 google sitemap.xml을 쿼리 할 때 문제가 발생했습니다.

는 조회 할 수 없습니다

<?xml version="1.0" encoding="utf-8"?> 
<urlset xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 
http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd" 
xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"> 
<url> 
    <loc>http://www.foo.com/index.htm</loc> 
    <lastmod>2010-05-11</lastmod> 
    <changefreq>monthly</changefreq> 
    <priority>1.0</priority> 
</url> 
<url> 
    <loc>http://www.foo.com/about.htm</loc> 
    <lastmod>2010-05-11</lastmod> 
    <changefreq>monthly</changefreq> 
    <priority>1.0</priority> 
</url> 
</urlset> 

는 조회 할 수 있습니다

<?xml version="1.0" encoding="utf-8"?> 
<urlset> 
<url> 
    <loc>http://www.foo.com/index.htm</loc> 
    <lastmod>2010-05-11</lastmod> 
    <changefreq>monthly</changefreq> 
    <priority>1.0</priority> 
</url> 
<url> 
    <loc>http://www.foo.com/about.htm</loc> 
    <lastmod>2010-05-11</lastmod> 
    <changefreq>monthly</changefreq> 
    <priority>1.0</priority> 
</url> 
</urlset> 

쿼리 :

XDocument xDoc = XDocument.Load(@"C:\Test\sitemap.xml"); 
var sitemapUrls = (from l in xDoc.Descendants("url") 
          select l.Element("loc").Value); 
foreach (var item in sitemapUrls) 
{  
    Console.WriteLine(item.ToString()); 
} 

은 무엇 이것에 대한 이유가 될 것입니까?

답변

7

XML의 "xmlns ="태그를 참조하십시오. 네임 스페이스를 지정해야합니다. 다음 코드 수정을 테스트하십시오.

XDocument xDoc = XDocument.Load(@"C:\Test\sitemap.xml"); 
XNamespace ns = "http://www.sitemaps.org/schemas/sitemap/0.9"; 

var sitemapUrls = (from l in xDoc.Descendants(ns + "url") 
        select l.Element(ns + "loc").Value); 
foreach (var item in sitemapUrls) 
{ 
    Console.WriteLine(item.ToString()); 
} 
+0

@Anthony - 예 감사합니다. 네임 스페이스가 반드시 사용 되어야만한다는 것을 알지 못했습니다. –

관련 문제