【发布时间】:2016-01-08 06:59:22
【问题描述】:
我在这里使用 linq 创建一个 xml,但没有获得所需的格式。这是我的代码
List<string> listvalue = new List<string>();
listvalue.Add("http://example.com/sample.html");
listvalue.Add("http://example.com/new.html");
foreach (string url in listvalue)
{
var document = new HtmlWeb().Load(url);
var urls = document.DocumentNode.Descendants("img")
.Select(e => e.GetAttributeValue("src", null))
.Where(s => !String.IsNullOrEmpty(s));
List<string> asList = urls.ToList();
GenerateXml(url, asList);
}
和
protected void GenerateXml(string url, List<string> listitems) //generateXml
{
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", nsImage),
new XElement(nsSitemap + "url",
new XElement(nsSitemap + "loc", url),
from urlNode in listitems
select new XElement(nsImage + "image",
new XElement(nsImage + "loc", 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.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>
<url>
<loc>http://example.com/new.html</loc>
<image:image>
<image:loc>http://example.com/newimage.jpg</image:loc>
</image:image>
<image:image>
<image:loc>http://example.com/newphoto.jpg</image:loc>
</image:image>
</url>
</urlset>
但在这里我得到一个 url 标签。如何做到这一点?有什么建议吗?
【问题讨论】:
-
您在第一段代码中调用
GenerateXmlinside your loop - 所以最后一次迭代只会使用XML。我怀疑你不想那样... -
@Jon Skeet:是的,我尝试过使用字典并在循环外生成 xml 中传递字典值。但我不知道如何在 linq 中获取格式
-
@Jon Skeet: Dictionary
> myDict = new Dictionary >(); myDict.Add(url, asList);GenerateXml(myDict);
标签: c# xml linq linq-to-xml