创建XML文件头

时间:2009-06-25 09:57:03

标签: c# asp.net xml

我想动态创建一个带有以下标题的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>

我应该如何创建这个urlset节点。

1 个答案:

答案 0 :(得分:3)

使用3.5,类似于:

XNamespace ns = "http://www.sitemaps.org/schemas/sitemap/0.9";
XNamespace xsi = "http://www.w3.org/2001/XMLSchema-instance";
XDocument doc = new XDocument(
    new XDeclaration("1.0", "utf-8", null),
    new XElement(ns + "urlset",
        new XAttribute(XNamespace.Xmlns + "xsi", xsi),
        new XAttribute(xsi + "schemaLocation", "http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd"),
        new XElement(ns + "url")
    )
);
// save/writeto
string s = doc.ToString();