1

我正在创建一个 xml 文件并尝试将命名空间附加到根节点。

    doc = new XDocument(new XElement(XName.Get("urlset",  "http://www.sitemaps.org/schemas/sitemap/0.9"),

但是,当我这样做时,它会在下一个节点(XDocument 的子节点)上附加一个空命名空间?

4

1 回答 1

1

Further XElements will have an empty namespace as you haven't specified any namespace for them. This then needs to be inidicated on child elements as it differs from the parent namespace. Unfortunately you need to specify the same namespace for all child documents if you want to "fix" this.

Luckily there's a shorthand code to do this:

XNamespace ns = "http://www.sitemaps.org/schemas/sitemap/0.9";

Then initialize all your elements like so:

new XElement(ns + ELEMENT_NAME, ...);

e.g.:

new XElement(ns + "urlset", ...);

instead of XName.Get.

于 2014-05-02T11:09:25.480 回答