站点地图未显示为xml格式

9

我有以下类用于生成网站地图:

public class SitemapItem
{
    public SitemapItem(string url)
    {
        this.Url = url;
        this.AlternateLinks = new List<SiteMapAlternateLink>();
    }

    public string Url { get; set; }

    public DateTime? LastModified { get; set; }

    public ChangeFrequency? ChangeFrequency { get; set; }

    public float? Priority { get; set; }

    public List<SiteMapAlternateLink> AlternateLinks { get; set; }
}

并且:

public class SiteMapAlternateLink
{
    public SiteMapAlternateLink(string url, string language)
    {
        this.Url = url;
        this.Language = language;
    }

    public string Url { get; set; }

    public string Language { get; set; }
}

现在,在我的控制器中,我使用以下代码填充SitemapItems列表,并从控制器返回它:

public class XmlSitemapResult : ActionResult
{
    private XNamespace nsSitemap = "http://www.sitemaps.org/schemas/sitemap/0.9";
    private XNamespace nsXhtml = "http://www.w3.org/1999/xhtml";

    private IEnumerable<SitemapItem> _items;

    public XmlSitemapResult(IEnumerable<SitemapItem> items)
    {
        _items = items;
    }

    public override void ExecuteResult(ControllerContext context)
    {
        string encoding = context.HttpContext.Response.ContentEncoding.WebName;
        XDocument sitemap = new XDocument(new XDeclaration("1.0", encoding, "yes"),
             new XElement(nsSitemap + "urlset", new XAttribute(XNamespace.Xmlns + "xhtml", nsXhtml),
                  from item in _items
                  select CreateItemElement(item)
                  )
             );

        context.HttpContext.Response.ContentType = "application/xml";
        context.HttpContext.Response.Charset = encoding;
        context.HttpContext.Response.Flush();
        context.HttpContext.Response.Write(sitemap.Declaration + sitemap.ToString());
    }

    private XElement CreateItemElement(SitemapItem item)
    {
        XElement itemElement = new XElement(nsSitemap + "url", new XElement(nsSitemap + "loc", item.Url.ToLower()));

        if (item.LastModified.HasValue)
            itemElement.Add(new XElement(nsSitemap + "lastmod", item.LastModified.Value.ToString("yyyy-MM-dd")));

        if (item.ChangeFrequency.HasValue)
            itemElement.Add(new XElement(nsSitemap + "changefreq", item.ChangeFrequency.Value.ToString().ToLower()));

        if (item.Priority.HasValue)
            itemElement.Add(new XElement(nsSitemap + "priority", item.Priority.Value.ToString(CultureInfo.InvariantCulture)));

        foreach (var alternateLink in item.AlternateLinks)
        {
            itemElement.Add(new XElement(nsXhtml + "link", 
                new XAttribute("rel", "alternate"),
                new XAttribute("hreflang", alternateLink.Language),
                new XAttribute("href", alternateLink.Url)));
        }

        return itemElement;
    }
}

现在的问题是,我的浏览器中看不到 XML 的原始格式,而只能看到文本内容,无法使用标准的 XML 查看器查看。这种情况在所有浏览器中都出现过,似乎是在添加 xhtml 模式后发生的。
希望有人能解决这个问题,谢谢!
编辑:如果删除与 xhtml 有关的内容,则浏览器可以将其显示为 xml。有什么想法吗?
编辑2:HTML:
 <urlset xmlns:xhtml="http://www.w3.org/1999/xhtml" xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
  <url>
    <loc>http://localhost:11149/en</loc>
    <changefreq>hourly</changefreq>
    <priority>0.6</priority>
    <xhtml:link rel="alternate" hreflang="en" href="http://localhost:11149/en"/>
    <xhtml:link rel="alternate" hreflang="nl" href="http://localhost:11149/nl"/>
  </url>
  <url>
    <loc>http://localhost:11149/en/buyandsell</loc>
    <changefreq>weekly</changefreq>
    <priority>1</priority>
    <xhtml:link rel="alternate" hreflang="en" href="http://localhost:11149/en/BuyAndSell"/>
    <xhtml:link rel="alternate" hreflang="nl" href="http://localhost:11149/nl/BuyAndSell"/>
  </url>
  <url>
    <loc>http://localhost:11149/en/partner</loc>
    <changefreq>weekly</changefreq>
    <priority>0.5</priority>
    <xhtml:link rel="alternate" hreflang="en" href="http://localhost:11149/en/Partner"/>
    <xhtml:link rel="alternate" hreflang="nl" href="http://localhost:11149/nl/Partner"/>
  </url>
  <url>
    <loc>http://localhost:11149/en/news</loc>
    <lastmod>2013-12-06</lastmod>
    <changefreq>daily</changefreq>
    <priority>0.6</priority>
    <xhtml:link rel="alternate" hreflang="en" href="http://localhost:11149/en/News"/>
    <xhtml:link rel="alternate" hreflang="nl" href="http://localhost:11149/nl/News"/>
  </url>
</urlset>

你需要展示你的控制器方法。另外,原始HTTP长什么样? - Liam
@Liam 我添加了HTML,控制器与此无关,因为它返回XmlSiteMapResult,除了填充项目列表之外,什么也不会发生。 - Julian
如果您查看站点地图(XDocument),此时它是否看起来像格式良好的XML? - Mike Beeler
据MSDN所述,这是一个有效的站点地图:http://msdn.microsoft.com/en-us/library/yy2ykkab(v=vs.100).aspx - radu florescu
每当我让一个网站验证时,网站地图都能够完美验证。但是我希望每当客户访问网站地图时,他可以通过浏览器的XML查看器来查看它。 - Julian
2个回答

3
这是我们为autoquoter.com生成网站地图的步骤。请查看http://www.autoquoter.com/aq/sitemap.xml
        var sitemap = new XDocument(
            new XDeclaration("1.0", "utf-8", "yes"),
            new XProcessingInstruction("xml-stylesheet",
                "type=\"text/xsl\" href=\"" + Url.AbsoluteAction("SitemapXsl", "Default") + "\""),
            new XElement(ns + "urlset",
                new XAttribute(XNamespace.Xmlns + "sitemap", ns),
                new XAttribute(XNamespace.Xmlns + "xhtml", xhtml), 
                nodeList));

        Response.AddHeader("X-Robots-Tag","noindex");
        return Content(sitemap.Declaration+"\r\n"+sitemap, "text/xml");

我们还使用一个xsl样式表来转换站点地图。这有助于那些不自动提供良好格式化程序的浏览器。请参阅http://www.autoquoter.com/aq/en/Default/SitemapXsl,了解我们正在使用的样式表。

这正是我一直在寻找的,所以您使用xls在浏览器中转换xml。不错的解决方案,谢谢! - Julian

1

编辑1:

看起来你可能会丢失一些xml特定的头文件:

查看此链接

这也可能是创建xml网站地图的有效示例:

Google的Sitemap xml 另一个示例
选项1 尝试这段代码(取自此处):

    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    public class Sitemap : IHttpHandler
    {
        private const string NAMESPACE = "http://www.sitemaps.org/schemas/sitemap/0.9";

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/xml";
            XmlDocument sitemapDocument = GetSitemapDocument();
            context.Response.Write(sitemapDocument.InnerXml);
        }

        #region Build sitemap document methods
        private XmlDocument GetSitemapDocument()
        {
            XmlDocument sitemapDocument = new XmlDocument();
            sitemapDocument.PreserveWhitespace = true;

            XmlDeclaration xmlDeclaration = 
                sitemapDocument.CreateXmlDeclaration("1.0", "UTF-8", string.Empty);
            sitemapDocument.AppendChild(xmlDeclaration);

            XmlElement urlset = sitemapDocument.CreateElement("urlset", NAMESPACE);
            sitemapDocument.AppendChild(urlset);

            List<SitemapPage> urls = GetSitemapPages();

            foreach (SitemapPage sitemapPage in urls)
            {
                XmlElement url = CreateUrlElement(sitemapDocument, sitemapPage);
                urlset.AppendChild(url);
            }
            return sitemapDocument;
        }

        private XmlElement CreateUrlElement(XmlDocument sitemapDocument, 
            SitemapPage sitemapPage)
        {
            XmlElement url = sitemapDocument.CreateElement("url", NAMESPACE);

            XmlElement loc = CreateElementWithText(sitemapDocument, "loc", 
                sitemapPage.Location);
            url.AppendChild(loc);

            if (sitemapPage.LastModificationDate.HasValue)
            {
                //lastmod must be a string that comforms to the W3C Datetime format
                string lastModValue = sitemapPage.LastModificationDate.Value.ToString(
                    "yyyy'-'MM'-'dd'T'HH':'mm':'ssK");
                XmlElement lastmod = CreateElementWithText(
                    sitemapDocument, "lastmod", lastModValue);
                url.AppendChild(lastmod);
            }

            if (!string.IsNullOrEmpty(sitemapPage.ChangeFrequency))
            {
                XmlElement changefreq = CreateElementWithText(sitemapDocument, 
                    "changefreq", sitemapPage.ChangeFrequency);
                url.AppendChild(changefreq);
            }

            if (sitemapPage.Priority.HasValue)
            {
                XmlElement priority = CreateElementWithText(sitemapDocument,
                    "priority", sitemapPage.Priority.Value.ToString(
                        CultureInfo.CreateSpecificCulture("en-US")));
                url.AppendChild(priority);
            }

            return url;
        }

        private XmlElement CreateElementWithText(
            XmlDocument document, string elementName, string text)
        {
            XmlElement element = document.CreateElement(elementName, NAMESPACE);

            XmlText elementValue = document.CreateTextNode(text);
            element.AppendChild(elementValue);

            return element;
        }
        #endregion

        private List<SitemapPage> GetSitemapPages()
        {
            List<SitemapPage> sitemapPages = new List<SitemapPage>();

            //Example implementation
            sitemapPages.Add(new SitemapPage("http://www.mydomain.com") 
                { ChangeFrequency = "daily", LastModificationDate = DateTime.Now, Priority = 1f });
            sitemapPages.Add(new SitemapPage("http://www.mydomain.com/aPage.aspx") 
                { ChangeFrequency = "daily", LastModificationDate = DateTime.Now, Priority = 0.8f });

            return sitemapPages;
        }

        private class SitemapPage
        {
            public SitemapPage(string location)
            {
                Location = location;
            }

            public string Location { get; private set; }
            public DateTime? LastModificationDate { get; set; }
            public string ChangeFrequency { get; set; }
            public float? Priority { get; set; }
        }

        public bool IsReusable
        {
            get
            {
                return true;
            }
        }
    }

选项2: 根据 MSDN,这是一个有效的站点地图:sitemap MSDN

查看此输出:

<siteMap>
  <siteMapNode title="Home" description="Home" url="~/default.aspx">
    <siteMapNode title="Products" description="Our products"
      url="~/Products.aspx">
      <siteMapNode title="Hardware" description="Hardware choices"
        url="~/Hardware.aspx" />
      <siteMapNode title="Software" description="Software choices"
        url="~/Software.aspx" />
    </siteMapNode>
    <siteMapNode title="Services" description="Services we offer"
        url="~/Services.aspx">
        <siteMapNode title="Training" description="Training classes"
          url="~/Training.aspx" />
        <siteMapNode title="Consulting" description="Consulting services" 
          url="~/Consulting.aspx" />
        <siteMapNode title="Support" description="Supports plans" 
          url="~/Support.aspx" />
    </siteMapNode>
  </siteMapNode>
</siteMap>

也许你应该尝试更改你的代码:

public class XmlSitemapResult : ActionResult
{
    private XNamespace nsSitemap = "http://www.sitemaps.org/schemas/sitemap/0.9";
    private XNamespace nsXhtml = "http://www.w3.org/1999/xhtml";

    private IEnumerable<SitemapItem> _items;

    public XmlSitemapResult(IEnumerable<SitemapItem> items)
    {
        _items = items;
    }

    public override void ExecuteResult(ControllerContext context)
    {
        string encoding = context.HttpContext.Response.ContentEncoding.WebName;
        XDocument sitemap = new XDocument(new XDeclaration("1.0", encoding, "yes"),
             new XElement(nsSitemap + "siteMap", new XAttribute(XNamespace.Xmlns + "xhtml", nsXhtml),
                  from item in _items
                  select CreateItemElement(item)
                  )
             );

        context.HttpContext.Response.ContentType = "application/xml";
        context.HttpContext.Response.Charset = encoding;
        context.HttpContext.Response.Flush();
        context.HttpContext.Response.Write(sitemap.Declaration + sitemap.ToString());
    }

    private XElement CreateItemElement(SitemapItem item)
    {
        XElement itemElement = new XElement(nsSitemap + "siteMapNode", new XElement(nsSitemap + "loc", item.Url.ToLower()));

        if (item.LastModified.HasValue)
            itemElement.Add(new XElement(nsSitemap + "lastmod", item.LastModified.Value.ToString("yyyy-MM-dd")));

        if (item.ChangeFrequency.HasValue)
            itemElement.Add(new XElement(nsSitemap + "changefreq", item.ChangeFrequency.Value.ToString().ToLower()));

        if (item.Priority.HasValue)
            itemElement.Add(new XElement(nsSitemap + "priority", item.Priority.Value.ToString(CultureInfo.InvariantCulture)));

        foreach (var alternateLink in item.AlternateLinks)
        {
            itemElement.Add(new XElement(nsXhtml + "link", 
                new XAttribute("rel", "alternate"),
                new XAttribute("hreflang", alternateLink.Language),
                new XAttribute("href", alternateLink.Url)));
        }

        return itemElement;
    }
}

都不行。我猜测在浏览器中无法将带有 XHTML 的 XML 显示为 XML。 - Julian
我仍然没有关于那个事实的确认,所以还没有答案。此外,这个问题对其他遇到同样问题的人也有帮助(并不是只有我一个人将xhtml添加到站点地图中,因为谷歌在他们自己的指南中也有)。此外,你不应该过分关注赏金。如果我得到答案,赏金将会被授予,如果赏金期结束,得分最高的答案将自动获得一半的积分,所以不用担心。 - Julian
朱利安,你找到答案了吗?我也遇到了备用节点的同样问题。 - Mansur Khan
@MansurKhan 没有,仍然没有得到任何满意的答案。我猜测当浏览器中有xhtml标签时,它就不会在XMLViewer中呈现。 - Julian
它不起作用是因为内容类型不正确。我在 .net 上尝试过了。 - radu florescu
显示剩余9条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接