/ / How to create XElement with namespaces - c#, xml, xml-namespaces, xelement

Як створити XElement з простору імен - c #, xml, xml-namespaces, xelement

I need to generate xml like that:

<urlset xmlns:video="http://www.google.com/schemas/sitemap-video/1.1"  xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url>
<loc>http://blabla</loc>
<video:video>
<video:player allow_embed="yes">http://blablabla</video:player_loc>
</video:video>
</url>

I can"t figure out the way to work with namespaces. I can"t even create urlset element properly, I"m trying:

 XNamespace _defaultNamespace = "http://www.sitemaps.org/schemas/sitemap/0.9";
XNamespace _videoNameSpace = "http://www.google.com/schemas/sitemap-video/1.1";

new XElement("urlset",new XAttribute(_defaultNamespace+"video",_defaultNamespace))

and it generates:

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<urlset p1:video="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:p1="http://www.sitemaps.org/schemas/sitemap/0.9">

what"s that p1 річ?

Відповіді:

3 для відповіді № 1

Namespace attributes are in xmlns namespace, so you should use XNamespace.Xmlns+ attributeName for declaring namespaces:

XNamespace ns = "http://www.sitemaps.org/schemas/sitemap/0.9";
XNamespace video = "http://www.google.com/schemas/sitemap-video/1.1";
var urlset = new XElement(ns + "urlset",
new XAttribute(XNamespace.Xmlns + "video", video));

Виробляє

<urlset xmlns:video="http://www.google.com/schemas/sitemap-video/1.1"
xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" />

Complete xml generation will look like:

var urlset = new XElement(ns + "urlset",
new XAttribute(XNamespace.Xmlns + "video", video),
new XElement(ns + "url",
new XElement(ns + "loc", "http:/blabla"),
new XElement(video + "video",
new XElement(video + "player",
new XAttribute("allow_embed", "yes"),
"http:/blabla"))));