【发布时间】:2016-01-07 14:23:33
【问题描述】:
我在这里尝试从列表中格式化 XML,但我没有得到正确的格式。这是我的代码:
protected void GenerateXml(string url, List<string> listitems) //generateXml
{
XNamespace nsXhtml = "http://www.w3.org/1999/xhtml";
XNamespace nsSitemap = "http://www.sitemaps.org/schemas/sitemap/0.9";
XNamespace nsImage = "http://www.google.com/schemas/sitemap-image/1.1";
var sitemap = new XDocument(new XDeclaration("1.0", "UTF-8", ""));
var urlSet =
new XElement(
nsSitemap + "urlset",
new XAttribute("xmlns", nsSitemap),
new XAttribute(XNamespace.Xmlns + "image", nsXhtml),
from urlNode in listitems
select
new XElement(
nsSitemap + "url",
new XElement(nsSitemap + "loc", url),
new XElement(nsSitemap + "image",
new XElement(nsSitemap + "imageloc", urlNode))));
sitemap.Add(urlSet);
sitemap.Save(System.Web.HttpContext.Current.Server.MapPath("/Static/sitemaps/Sitemap-image.xml"));
}
... 并获得如下格式:
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:image="http://www.w3.org/1999/xhtml">
<url>
<loc>http://example.com/intl/cars/new-models/the-new-s90</loc>
<image>
<imageloc>http://example.com/static/images/volvo-logo-scaled.png</imageloc>
</image>
</url>
<url>
<loc>http://example.com/intl/cars/new-models/the-new-s90</loc>
<image>
<imageloc>http://assets.example.com/intl/~/media/images/galleries/new-cars/packshots/small/allnew_xc90-side_2.png</imageloc>
</image>
</url>
</urlset>
但我需要这种格式:
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
xmlns:image="http://www.google.com/schemas/sitemap-image/1.1">
<url>
<loc>http://example.com/sample.html</loc>
<image:image>
<image:loc>http://example.com/image.jpg</image:loc>
</image:image>
<image:image>
<image:loc>http://example.com/photo.jpg</image:loc>
</image:image>
</url>
</urlset>
有什么建议吗?
【问题讨论】:
-
如果你想要
image:image节点,你为什么要使用new XElement(nsSitemap + "image"而不是new XElement(nsImage + "image"? -
如果您想在
url中添加多个image,则需要将new XElement(nsSitemap + "url"移到from之外
标签: c# xml linq linq-to-xml