Remove unused xmlns namespaces from an XmlDocument?

My software receives XmlDocuments created by a software library. The
XmlDocuments I receive often contain many unused xmlns namespaces,
such as:

<ns1:Message xmlns:ns1="http://www.domain1.com/v1" xmlns:ns2="http://
www.domain2.com/v1" xmlns:ns3="http://www.domain3.com/v1"
xmlns:ns4="http://www.domain4.com/v1" xmlns:ns5="http://
www.domain5.com/v1"><ns1:Ack ns1:messageId="1"
ns1:dateTimeSent="2009-12-31T01:30:14.0462064Z" /></ns1:Message>

As you can see, ns2 through ns5 are extraneous.

Sometimes, more than 50% of the message is just unused namespaces and
I would like to remove them after I receive the XmlDocument (cannot
change the library) and before I send the message over the wire.

Are there any Xml-related classes or methods (C#, .NET 3.5) that I can
use to parse the XmlDocument and remove the unused namespaces?
0
mzarlenga
1/2/2010 6:21:23 AM
dotnet.xml 7266 articles. 0 followers. Follow

6 Replies
7128 Views

Similar Articles

[PageSpeed] 16

mzarlenga wrote:
> My software receives XmlDocuments created by a software library. The
> XmlDocuments I receive often contain many unused xmlns namespaces,
> such as:
> 
> <ns1:Message xmlns:ns1="http://www.domain1.com/v1" xmlns:ns2="http://
> www.domain2.com/v1" xmlns:ns3="http://www.domain3.com/v1"
> xmlns:ns4="http://www.domain4.com/v1" xmlns:ns5="http://
> www.domain5.com/v1"><ns1:Ack ns1:messageId="1"
> ns1:dateTimeSent="2009-12-31T01:30:14.0462064Z" /></ns1:Message>
> 
> As you can see, ns2 through ns5 are extraneous.
> 
> Sometimes, more than 50% of the message is just unused namespaces and
> I would like to remove them after I receive the XmlDocument (cannot
> change the library) and before I send the message over the wire.
> 
> Are there any Xml-related classes or methods (C#, .NET 3.5) that I can
> use to parse the XmlDocument and remove the unused namespaces?

Does XmlDocument mean you have a System.Xml.XmlDocument? Or do you get 
an XML document you could parse with LINQ to XML 
(System.Xml.Linq.XDocument)?

One way to get rid of unused namespaces is to simply get rid of any 
namespace declaration attributes, then serialize the document and the 
serializer will take care of adding any namespace declarations that are 
necessary to have a namespace well-formed document:

So with your above sample document the code

             XDocument doc = XDocument.Load("input.xml", 
LoadOptions.PreserveWhitespace);
             doc.Descendants().Attributes().Where(a => 
a.IsNamespaceDeclaration).Remove();
             doc.Save("output.xml", SaveOptions.DisableFormatting);

would output

<Message xmlns="http://www.domain1.com/v1"><Ack p2:messageId="1" 
p2:dateTimeSent="2009-12-31T01:30:14.0462064Z" 
xmlns:p2="http://www.domain1.com/v1" /></Message>

That document is semantically equivalent to the one you posted, only the 
serializer has choosen to put the elements in the default namespace and 
to use the prefix 'p2' for the attributes.

Does that suffice for your needs?

-- 

	Martin Honnen --- MVP XML
	http://msmvps.com/blogs/martin_honnen/
0
Martin
1/2/2010 12:36:44 PM
Martin Honnen wrote:
> mzarlenga wrote:
>> My software receives XmlDocuments created by a software library. The
>> XmlDocuments I receive often contain many unused xmlns namespaces,
>> such as:
>>
>> <ns1:Message xmlns:ns1="http://www.domain1.com/v1" xmlns:ns2="http://
>> www.domain2.com/v1" xmlns:ns3="http://www.domain3.com/v1"
>> xmlns:ns4="http://www.domain4.com/v1" xmlns:ns5="http://
>> www.domain5.com/v1"><ns1:Ack ns1:messageId="1"
>> ns1:dateTimeSent="2009-12-31T01:30:14.0462064Z" /></ns1:Message>
>>
>> As you can see, ns2 through ns5 are extraneous.
>>
>> Sometimes, more than 50% of the message is just unused namespaces and
>> I would like to remove them after I receive the XmlDocument (cannot
>> change the library) and before I send the message over the wire.
>>
>> Are there any Xml-related classes or methods (C#, .NET 3.5) that I can
>> use to parse the XmlDocument and remove the unused namespaces?
> 
> Does XmlDocument mean you have a System.Xml.XmlDocument? Or do you get 
> an XML document you could parse with LINQ to XML 
> (System.Xml.Linq.XDocument)?
> 
> One way to get rid of unused namespaces is to simply get rid of any 
> namespace declaration attributes, then serialize the document and the 
> serializer will take care of adding any namespace declarations that are 
> necessary to have a namespace well-formed document:
> 
> So with your above sample document the code
> 
>             XDocument doc = XDocument.Load("input.xml", 
> LoadOptions.PreserveWhitespace);
>             doc.Descendants().Attributes().Where(a => 
> a.IsNamespaceDeclaration).Remove();
>             doc.Save("output.xml", SaveOptions.DisableFormatting);
> 
> would output
> 
> <Message xmlns="http://www.domain1.com/v1"><Ack p2:messageId="1" 
> p2:dateTimeSent="2009-12-31T01:30:14.0462064Z" 
> xmlns:p2="http://www.domain1.com/v1" /></Message>
> 
> That document is semantically equivalent to the one you posted, only the 
> serializer has choosen to put the elements in the default namespace and 
> to use the prefix 'p2' for the attributes.
> 
> Does that suffice for your needs?

I think it will. I'll try it and get back to you. Thank you.
0
Mike
1/2/2010 5:57:56 PM
On Jan 2, 4:36=A0am, Martin Honnen <mahotr...@yahoo.de> wrote:
> > Are there any Xml-related classes or methods (C#, .NET 3.5) that I can
> > use to parse the XmlDocument and remove the unused namespaces?
....

> Does XmlDocument mean you have a System.Xml.XmlDocument? Or do you get
> an XML document you could parse with LINQ to XML
> (System.Xml.Linq.XDocument)?
>
> One way to get rid of unused namespaces is to simply get rid of any
> namespace declaration attributes, then serialize the document and the
> serializer will take care of adding any namespace declarations that are
> necessary to have a namespace well-formed document:
>
> So with your above sample document the code
>
> =A0 =A0 =A0 =A0 =A0 =A0 =A0XDocument doc =3D XDocument.Load("input.xml",
> LoadOptions.PreserveWhitespace);
> =A0 =A0 =A0 =A0 =A0 =A0 =A0doc.Descendants().Attributes().Where(a =3D>
> a.IsNamespaceDeclaration).Remove();
> =A0 =A0 =A0 =A0 =A0 =A0 =A0doc.Save("output.xml", SaveOptions.DisableForm=
atting);
>
> would output
>
> <Message xmlns=3D"http://www.domain1.com/v1"><Ack p2:messageId=3D"1"
> p2:dateTimeSent=3D"2009-12-31T01:30:14.0462064Z"
> xmlns:p2=3D"http://www.domain1.com/v1" /></Message>
>
> That document is semantically equivalent to the one you posted, only the
> serializer has choosen to put the elements in the default namespace and
> to use the prefix 'p2' for the attributes.
>
> Does that suffice for your needs?

I think it will. I'll try it and get back to you. Thank you.
0
mzarlenga
1/2/2010 6:38:05 PM
On Jan 2, 10:38=A0am, mzarlenga <mzarle...@gmail.com> wrote:
> > =A0 =A0 =A0 =A0 =A0 =A0 =A0XDocument doc =3D XDocument.Load("input.xml"=
, LoadOptions.PreserveWhitespace);
> > =A0 =A0 =A0 =A0 =A0 =A0 =A0doc.Descendants().Attributes().Where(a =3D> =
> > a.IsNamespaceDeclaration).Remove();
> > =A0 =A0 =A0 =A0 =A0 =A0 =A0doc.Save("output.xml", SaveOptions.DisableFo=
rmatting);
....
> > Does that suffice for your needs?

> I think it will. I'll try it and get back to you. Thank you.

I can't get this to build with VS 2008 professional, console app,
project's target framework is .NET 3.5

....
using System.Collections;
using System.Collections.Generic;
using System.Xml.Linq;
....
XDocument doc =3D XDocument.Load("input.xml",
LoadOptions.PreserveWhitespace);
doc.Descendants().Attributes().Where(a =3D>
a.IsNamespaceDeclaration).Remove();

Error	504 (on doc.Descendants()...")
'System.Collections.Generic.IEnumerable<System.Xml.Linq.XAttribute>'
does not contain a definition for 'Where' and no extension method
'Where' accepting a first argument of type
'System.Collections.Generic.IEnumerable<System.Xml.Linq.XAttribute>'
could be found (are you missing a using directive or an assembly
reference?)

Been through the MSDN site but I keep hitting an information roadblock
at XDocument.Descendants.  Not sure where to proceed from there to get
to .Attributes().Where()

What using or assembly reference might I be missing?
0
mzarlenga
1/2/2010 10:32:42 PM
mzarlenga wrote:

> I can't get this to build with VS 2008 professional, console app,
> project's target framework is .NET 3.5
> 
> ...
> using System.Collections;
> using System.Collections.Generic;
> using System.Xml.Linq;

You also need
   using System.Linq;
and a reference to System.Core.dll.



-- 

	Martin Honnen --- MVP XML
	http://msmvps.com/blogs/martin_honnen/
0
Martin
1/3/2010 11:11:43 AM
Thank you for the pointers, Martin, you got me going in the right
direction.

I ended up with a different solution, once I understood that I could
XmlSerializer.Serialize() without the XmlSerializerNamespaces()
parameter and still get semantically correct Xml.

Works great!
0
mzarlenga
1/3/2010 8:02:13 PM
Reply:

Similar Artilces:

Removing My Tasks
A project was completed and is 100%. The tasks are "closed for updates". I have selected the tasks and and deleted within My Tasks but they remain showing in "My Tasks" How do i permantly remove? Michael J -- Are you the project manager of this project? From your description, it sounds like you are the PM. If so, you have made a huge mistake selecting the completed tasks and clicking the Delete button. In doing so, this will set a Delete Assignment Request back to your PM (I assume the PM is you) for each deleted task. If the PM approves these Delete...

Remove the Personal Folders
I can't delete my Personal Folders in Folder list. When I deleted it, it appeared this message : The operation failed. An object could not be found. And i also want to delete it in following step: 1 right click the outlook irons 2 click the properties 3 but i can't see my personal folders in the service bar why??? Personal Folder is the default, it points to the pst file Why are you trying to delete? If you have multiple Personal Folders, ie multiple pst's, close it "eto coffee" <anonymous@discussions.microsoft.com> wrote in message news:210001c4a210$b58671c0$...

Removal of STF files?
I have had a few unplanned down times wit h exchange which seem to be corrected, however the .stf files from each of these have not been deleted when the information store was restarted.. Is it ok to delete these files? The STF file is one of the file for the Store, why would want to delete it manually? -- Mark Fugatt Exchange MVP http://www.exchangetrainer.com http://www.msexchange.org "Derek Schauland" <derek@briess.com> wrote in message news:6296D98F-4041-4980-B6FB-00D1C2B6C28A@microsoft.com... >I have had a few unplanned down times wit h exchange which seem to be ...

Removing E2K3 FE server from Org and Win2K3AD, for rebuilding
If I am using an E2K3 server as a dedicated FE server, with another E2K3 server on the backend, if I want to rebuild the FE server from scratch can I simply: 1. Use the Exchange System Manager on the backend server, and delete the server from the Exchange site.. 2. Delete the FE server's account from my Win2K3 AD domain... 3. Rebuild the FE server and readd it to both AD and the E2K3 organization? Robert, If you want to retain the same name for the FE computer then the steps are even easier: 822945 How to Move Exchange 2003 to New Hardware and Keep the Same Server Name http://support...

Macro to remove rows?
Hi, I receive thousands of rows of data from an extract that comes from a database. The data extract automatically generates page headers that need to be removed, and I would love to automate this process. The headers do have a pattern to them, but I'm not clever enough to figure out a good way to use that to write a macro. The first row of the header starts with hyphens ------------------------------- Then there's a variable number of rows of header data to delete followed by another row of hyphens ------------------------------- Then 2 additional rows that must be deleted. The nu...

Impact of removal of Item from Public Folder Instance Folder
I am a new administrator for a large Exchange 2003 organization that is just getting off the ground. We had to recently reconfigure replication of a public folder. It was set to replicate content to a number of servers when it really was meant to reside only on a couple of servers. To make the change, from within ESM I went to our Enterprise Administrative Group and to the Folders folder, to Public Folders, to the top level folder that had been created for the branch office to migrate their public folders into and I went into the properties of this branch office public folder then to the repli...

Removing links between spreadsheets
Is there a way to remove links without pasting info as values when sending a file via email as i wish to keep other formulas many thanks If you have Excel 2002 or 2003 you can use Edit, Break Links. Otherwise, if you do not have too many links you can convert them to values by selecting each one and doing an Edit, F9, Enter. -- Jim Rech Excel MVP "mark gill" <anonymous@discussions.microsoft.com> wrote in message news:1d35001c422db$22248f20$a101280a@phx.gbl... | Is there a way to remove links without pasting info as | values when sending a file via email as i wish to k...

Removing xmlns="" from XmlTextWriter output
I am creating an XmlDocument in code and then using XmlTextWriter via doc.WriteTo(xwriter) to output the result to a text box. I have a root element that defines a default namespace. However, the sub-elements are created without any namespaces like so: XmlElement elem = doc.CreateElement("Foo"); root.AppendChild(elem); but in the output I get this: <?xml version="1.0" encoding="utf-8"?> <Root xmlns="http://tempuri.org"> <Foo xmlns="" /> </Root> How can I get rid of the ' xmlns="" ' attribut...

Remove caption that states which printer you are printing to.
I have been asked how to get rid of the caption that tells you what printer you are sending your printing to. "Sue" <Sue@discussions.microsoft.com> wrote in message news:42E9E6E2-756C-4827-8DEF-EF3E2C48139D@microsoft.com > I have been asked how to get rid of the caption that tells you what > printer you are sending your printing to. I would suggest that's a WINDOWS problem not Outlook. ...

'Closing' chart window *and* removing chart using VBA
Hello, When an embedded chart is in its window, clicking the 'X' of the window merely removes the window but does not remove the chart (chart object). Is there a way to remove/delete the chart when clicking on the 'X'? In other words, can an an event of some sort that recognizes the Window becoming invisible, be used delete the chart? Would this sort of this be solved with Windows handles and APIs...? Thanks/Cheers. Marc R. Bertrand I suspect that you can probably do what you want with some amount of event / Win API programming. However, as pointed out in the response t...

xmlns:g
I found some sample code to construct an rss feed and am trying to modify it to match Google's specs at: http://www.google.com/base/rss_specs.html, but without knowing much about XML. Their samples show the namespace declaration in the rss tag, I tried it both ways with the same result. It seems reasonably clear, add a namespace: XmlElement docNode = rssDoc.CreateElement("rss"); XmlAttribute attr = rssDoc.CreateAttribute("version"); attr.Value = "2.0"; docNode.Attributes.Append(attr); XmlAttribute attr1 = rssDoc....

Removing grids
Hi, I've got a problem with a file with 4 columns and many rows (approx. 30000). And the problem is that all data is in grid, and when I open this file it takes me more than 10 minutes (processor athlon 2600+, 768MB RAM) and IMHO it's too long. When the file is already opened I try to remove grid and save the file. And then opening the file takes a few seconds. And the question is: how can I decrease opening time of the file. I think that I can't use MS EXcel for opening and removing grid (time), and if anybody knows how to do this in other way i will be appreciate. I see ...

Finding unused objects
Using the following DMV I get to know which of the objects in the DB is in use dm_exec_trigger_stats, dm_exec_procedure_stats, dm_db_index_usage_stats Is there a DMV to have this data about a View? Gal (Gal@discussions.microsoft.com) writes: > Using the following DMV I get to know which of the objects in the DB is > in use dm_exec_trigger_stats, dm_exec_procedure_stats, > dm_db_index_usage_stats > Is there a DMV to have this data about a View? If you want to know which are the unused procedures: SELECT o.name FROM sys.objects o WHERE o.type = 'P' ...

Completely Remove Outlook 2000 profile
I'm trying to completely remove an outlook 2000 profile... including all email and calendar reminders. Can't seem to find the correct procedure in using help files. Thanks in advance, Jorge Did you remove the PST file associated with that profile? "Jorge" <anonymous@discussions.microsoft.com> wrote in message news:041f01c39a84$4d2a8a60$a401280a@phx.gbl... > I'm trying to completely remove an outlook 2000 profile... > including all email and calendar reminders. > > Can't seem to find the correct procedure in using help > files. ...

add a node to XMLDocument
Hi, I'm new to XML programming. I'm writing a program in Visual Basic.Net that retrieves XML data from eBay. I want to store the results of a query in an xmlDocument. Here is an example, I pass an item number, and get back XML information about that listing. Response format here. http://developer.ebay.com./DevZone/shopping/docs/CallRef/GetSingleItem.html#Response I have an XML document that keeps a list of information about various items. I only use a few of the fields there. <?xml version="1.0" encoding="utf-8"?> <ItemList> &...

Removing Past Layaway Data
Hello, Is there a quick way to remove all past layaways from the RMS SQL Database? When layaways were used in QuickSell 2000 at my store, they were never entered correctly. I would like to remove all old layaway data / information, in one quick process. The only way I have found to do this is deleting each single line at a time. Thank you, Ryan ...

Problems with removing old Deleted Items files
Our Exchange server went from version 4.0 and is now at 5.5 w/SP4 and is running in a cluster. I have some users that, although OutLook says that there are no deleted items, and, they'll religiously delete what they do have every time that they exit OutLook, Exchange Administrator shows a lot (50-80 MB, in some cases) of Deleted Items. I understand that there was a bug with either 4.0, or, in going from 4.0 to 5.5 that would cause retention of Deleted Items? If this is my problem, how can I delete this files? Thanks! This is quite normal if you have deleted item retention enabled. ...

.Net Compiler Creating Wrong Namespace In Discovery file
I have two web services running on my server. One is ABC.asmx the other is ABC_D.asmx both are in seperate folders... When I compile the project for abc.asmx the Namespace information in the resource.map.vb file is http:\\127.0.0.1\ABC_D Do you know what may be causing this, Thanks for the help ...

permissions problem removing office 2004
I'm having trouble removing Office 2004 using the Remove Office program, which tells me "You do not have permission to remove Office" and to log into the same user account that I used to install it. However, the problem is that I can't log into that user account because it has been deleted and replaced with another (which I had to do to solve another problem). Would anyone have any thoughts on how I might be able to remove it? Any help would be appreciated, thanks. susie ...

Cancelled out of account removal, but mail disappeared anyway?
I got tired of getting prompted for an email account I no longer have, so I figured I should remove the account. I started to do that, saw a message that it would take awhile, realized that maybe "removing the account" meant more than trying to sync it, so I hit Cancel. When the dialog box closed, all the folders from the old account had been removed. Is there any way to get them back? I haven't closed WLM yet. (slightly panicky, as that was over a decades' worth of archived mail) Your first message should have been stating that the account messages will be r...

How to remove title bar
Is there anyway that I can remove the title bar from my forms. It's making them look cluttered in places. If you turn off all the buttons and have a blank caption, you can then set the form to have no border. If you then want a small border, create one using a rectangle (box) control. -- Arvin Meyer, MCP, MVP http://www.datastrat.com http://www.mvps.org/access http://www.accessmvp.com "RitchieJHicks" <RitchieJHicks@discussions.microsoft.com> wrote in message news:C1EBC60E-F595-4545-9E78-F37FF7C50ED6@microsoft.com... > Is there anyway that I can remove the title ba...

HOWTO Overcome missing namespace declaration in root node
I am having a problem deserializing XML when the root node is missing a namespace declaration. My Type has an XmlTypeAttribute with a namespace defined. If I attempt to deserialize the XML, I get the dreaded <elementname xmlns=''> was not expected exception. If I comment out the XmlTypeAttribute, it works just fine. Just so you know, when I instantiate an instance of an XmlSerializer, I pass a default namespace to the ctor. Unfortunately that doesn't seem to work. So, how can I get the XmlSerializer to accept XML that is missing namespace declarations? -- -- David ...

How to "Remove" #REF!??? #2
Hi Frank Thanks for your help! It worked perfectly! Hi Gord Thanks for your comments... I learnt alot from your comments... I hav to apologise for not posting a clearer post... The formula I had wa GetPivotData(....) hence if the specified field in the formula is no there, then it will become #REF!. Hope this will help to clear th confusion... Cheer -- hc ----------------------------------------------------------------------- hce's Profile: http://www.excelforum.com/member.php?action=getinfo&userid=351 View this thread: http://www.excelforum.com/showthread.php?threadid=26809 ...

Removing attachments from multiple emails #2
I need to remove attachments (pictures) from many emails, possibly hundreds of emails, which are sorted in different folders. I want to keep the emails but can safely remove the attachments, is there an easy way to remove all the attachments? Nick "Nick" <njframe@gmail.com> wrote in message news:OItQgzx8GHA.4604@TK2MSFTNGP03.phx.gbl... >I need to remove attachments (pictures) from many emails, possibly hundreds >of emails, which are sorted in different folders. > > I want to keep the emails but can safely remove the attachments, is there > an easy way...

remove weekends in timeline
How do I remove weekends in a visio Timeline? I couldn't find a way to do this in a Visio Timeline. You might add shaded intervals to at least show the weekends, if that helps. Alternately, you could just work seven days a week so that there are no weekends. My boss likes this approach. ;-) "ttran" <ttran@discussions.microsoft.com> wrote in message news:C963C865-F80B-48E1-9E3D-8C4D7E8B8E27@microsoft.com... > How do I remove weekends in a visio Timeline? Nice, help get us out of the recession! :) -- Hope this helps, Chris Roth Visio MVP Visio Guy: Sma...