Thursday, April 5, 2012

Avoiding xmlns="" while appending new XML node

To avoid xmlns="" attibute which gets added when you append a new node in to your existing XML document.

The main point is that the namespace of a node is determined when you create it, not when you insert it.

So when you create your new nodes you need to make sure you create them under a proper namespace.
If you already have a node and that is in no namespace and you insert it somewhere into a node that is in a namespace then
the serializer has to add the xmlns="" to ensure the node remains in no namespace.
That is how the DOM works, there is no way to change that.


So as already suggested, make sure you create nodes in the namespace you want them in.

Check here the detail how I have used below line

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


Try this below working code, to run the sample.

XDocument xDoc = XDocument.Load(Server.MapPath("sitemap.xml"));
XNamespace xN = "http://www.sitemaps.org/schemas/sitemap/0.9";


XElement xUrlNode = new XElement(xN + "url");
XElement xLocNode = new XElement(xN + "loc","my Location");
XElement xlastmod = new XElement(xN + "lastmod", "new()");
XElement xchangefreq = new XElement(xN + "changefreq", "weekly");
XElement xpriority = new XElement(xN + "priority", "0.8");


//Lets insert the nodes in reverse case

xUrlNode.Add(xLocNode);

//Add the child node in the URL node
xUrlNode.Add(xlastmod);
xUrlNode.Add(xchangefreq);
xUrlNode.Add(xpriority);

//Add the URL Node
xDoc.Root.Add(xUrlNode);

string seeOutPutHere = xDoc.ToString();

xDoc.Save(Server.MapPath("sitemap.xml"));



This was my sitemap.xml input before I ran the code.

<?xml version="1.0" encoding="utf-8"?&>t;
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" 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"&>t;
<url&>t;
<loc&>t;http://www.eureferendum.com/blogview.aspx?blogno=11</loc&>t;
<lastmod&>t;2012-03-21</lastmod&>t;
<changefreq&>t;weekly</changefreq&>t;
<priority&>t;0.8</priority&>t;
</url&>t;
</urlset&>t;



This will give you output as below.

<?xml version="1.0" encoding="utf-8"?&>t;
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" 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"&>t;
<url&>t;
<loc&>t;http://www.eureferendum.com/blogview.aspx?blogno=11</loc&>t;
<lastmod&>t;2012-03-21</lastmod&>t;
<changefreq&>t;weekly</changefreq&>t;
<priority&>t;0.8</priority&>t;
</url&>t;
<url&>t;
<loc&>t;my Location</loc&>t;
<lastmod&>t;new()</lastmod&>t;
<changefreq&>t;weekly</changefreq&>t;
<priority&>t;0.8</priority&>t;
</url&>t;
</urlset&>t;

No comments:

Post a Comment