473,394 Members | 1,750 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,394 software developers and data experts.

How do you remove Namespaces in XMLs

4
Hi All,

I need to remove all namespaces from xml file shown after c sharp code (also been attached).
The problem is that I am getting the following error being returned by one of the functions

{System.Xml.XmlException: The prefix '' cannot be redefined from '' to 'http://sample.response.power.core.com' within the same start element tag.
at System.Xml.XmlWellFormedWriter.PushNamespaceExplic it(String prefix, String ns)
at System.Xml.XmlWellFormedWriter.WriteEndAttribute()
at System.Xml.Linq.ElementWriter.WriteStartElement(XE lement e)
at System.Xml.Linq.ElementWriter.WriteElement(XElemen t e)
at System.Xml.Linq.XElement.WriteTo(XmlWriter writer)
at System.Xml.Linq.XNode.GetXmlString(SaveOptions o)
at System.Xml.Linq.XNode.ToString()
}
Can somebody think of an alternative way of removing namespaces within an xml file or figure out the issue with my code please?

Code:
Expand|Select|Wrap|Line Numbers
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Xml;
  6. using System.IO;
  7. using System.Xml.Serialization;
  8.  
  9. namespace ConsoleApplication2
  10. {
  11.     class Program
  12.     {
  13.         public static string RemoveAllNamespaces(string xmlDocument)
  14. {
  15. XElement xmlDocumentWithoutNs = RemoveAllNamespaces(XElement.Parse(xmlDocument));
  16. return xmlDocumentWithoutNs.ToString();
  17. }
  18. //Core recursion function
  19. private static XElement RemoveAllNamespaces(XElement xmlDocument)
  20. {
  21. if (!xmlDocument.HasElements)
  22. {
  23. XElement xElement = new XElement(xmlDocument.Name.LocalName);
  24. xElement.Value = xmlDocument.Value;
  25. foreach (XAttribute attribute in xmlDocument.Attributes())
  26. xElement.Add(attribute);
  27. return xElement;
  28. }
  29. return new XElement(xmlDocument.Name.LocalName, xmlDocument.Elements().Select(el => RemoveAllNamespaces(el)));
  30. }
  31.  
  32.  
  33.  
  34.         static void Main(string[] args)
  35.         {
  36.             XmlDocument document = new XmlDocument();
  37.             document.Load("C:\\temp\\xmlfile.xml");
  38.  
  39.             XmlNamespaceManager mgr = new XmlNamespaceManager(document.NameTable);
  40.             mgr.AddNamespace("ns", "http://sample.stock.power.vno.com");
  41.             XmlNodeList nodes = document.SelectNodes("/GetOrderMessagesResponse/ns:orderResponses/ns:OrderResponse", mgr);
  42.             foreach (XmlNode n in nodes)
  43.             {
  44.  
  45.                 XmlDocument outdoc = new XmlDocument();
  46.                 XmlNode targetNode = outdoc.CreateElement("OrderResponse");
  47.                 targetNode = outdoc.ImportNode(n, true);
  48.                 targetNode.Attributes.RemoveAll();
  49.                 outdoc.ImportNode(targetNode, true);
  50.                 outdoc.AppendChild(targetNode);
  51.  
  52.                 XmlSerializer serializer = new XmlSerializer(outdoc.GetType());
  53.                 XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
  54.                 ns.Add("","");
  55.                 StringWriter myWriter = new StringWriter();
  56.                 serializer.Serialize(myWriter, outdoc, ns);
  57.  
  58.                 String temp = myWriter.ToString();
  59.                 Console.WriteLine(RemoveAllNamespaces(temp));              
  60.  
  61.  
  62.                 Console.ReadKey();
  63.             } 
  64.  
XMLFILE:
<?xml version="1.0" encoding="utf-8"?>
<PaymentReference xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Stock xsi:nil="true" xmlns="http://bloom.stock.power.vno.com" />
<Response xmlns="http://sample.stock.power.vno.com">
<Order>
<OrderDateTime>2012-09-16T09:28:10+01:00</OrderDateTime> <addressloc>XL11046560</addressloc>
<appReference xsi:nil="true" />
<buyerID>SN999</buyerID>
<cancellationReason xsi:nil="true" />
<caseReference xsi:nil="true" />
<cessationReason xsi:nil="true" />
<cssDatabaseCode xsi:nil="true" />
<currentSPName xsi:nil="true" />
<liners xsi:nil="true" />
<Notes>
<Comment xmlns="http://sample.document.power.vno.com"> <completionNo>No019</completionNo>
<message>Incorrect ID</message>
</Comment>
</Notes>
<newRcfOrCrServiceId xsi:nil="true" />
<notes xsi:nil="true" />
<numberOfOrders xsi:nil="true" />
<parentOrderRef xsi:nil="true" />
<postcode xsi:nil="true" />
<projectId xsi:nil="true" />
<serviceId xsi:nil="true" />
<Address>
<addressCode xsi:nil="true" xmlns="http://sample.response.power.core.com" /> <addressRegion xmlns="http://sample.response.power.core.com">NW01254</addressRegion>
<Nation xmlns="http://sample.response.power.core.com">United Kingdom</Nation>
<county xsi:nil="true" xmlns="http://sample.response.power.core.com" /> <organisationType xsi:nil="http://sample.response.power.core.com" /> </Address>
<status>
<created>2012-09-16T09:28:31+01:00</created> <Id>Core24</Id>
<operatorname>test_Name</operatorname>
</status>
<subOrderType>PROVIDE_GOLDEN</subOrderType> <telephoneNumber>01125412514</telephoneNumber> <validity>false</validity> <vatCode xsi:nil="true" />
</Order>
</Response>
</PaymentReference>
Attached Files
File Type: txt xmlfile.txt (1.7 KB, 730 views)
Oct 21 '12 #1

✓ answered by bekets

You can use the following function to remove all namespaces

static XElement stripNS(XElement root)
{
return new XElement(
root.Name.LocalName,
root.HasElements ?
root.Elements().Select(el => stripNS(el)) :
(object)root.Value
);
}

2 15264
bekets
4
Hi Zmbd,

I've formatted the code as requested.

many thanks.
Oct 23 '12 #2
bekets
4
You can use the following function to remove all namespaces

static XElement stripNS(XElement root)
{
return new XElement(
root.Name.LocalName,
root.HasElements ?
root.Elements().Select(el => stripNS(el)) :
(object)root.Value
);
}
Oct 23 '12 #3

Sign in to post your reply or Sign up for a free account.

Similar topics

18
by: Steven Bethard | last post by:
In the "empty classes as c structs?" thread, we've been talking in some detail about my proposed "generic objects" PEP. Based on a number of suggestions, I'm thinking more and more that instead of...
1
by: Kyndig | last post by:
Hi group, I am working on retrieving/storing information in a MySQL database that requires the rows of the db scheme to be expandable. As an example of what I am trying to do: You want to store...
1
by: Greg Rothlander | last post by:
I posted this a few days ago and didn't get any response. I try again but ask it a little differently. I'm recieving any XML document from a client and I need to convert it to an ASCII delimited...
5
by: EMonaco | last post by:
All, I have a simple C# window app under MyApp namespace it has a class Form1. I've added another class .cs file. Now this class I want to share with many projects, so I figured I'd change this...
1
by: Richard | last post by:
Hi, I would like to strip all of the "xmlns" attributes out of an XmlDocument. I coded a function that recurses nodes and calls: XmlNode n = node.Attributes.RemoveNamedItem("xmlns"); After...
4
by: michaeltorus | last post by:
H I've got an n-tier web app. The namespaces follow the layers in that I've got a DAL namespace, a BOL namespace and a WEB namespac What I'm tring to decide is the naming convention for my...
2
by: Joe Bloggs | last post by:
Hi, I am trying to remove the namespace in the root node in the following XML, <ordersHistory xmlns="http://tempuri.org/Orders.xsd"> <order number="PO-1" added="12/12/2002"> <client...
0
by: Zyronne | last post by:
Hello.. I wanted to know if this is possible. Its supposedly for Content management purposes. a website will use local xmls as data so it acts as a preview before this xmls be sent on...
0
by: Nick | last post by:
Hi, I need to compare two xml files. Which contain multiple xml datas based on a key. So for eg. I have two xmls A.xml and B.xml. A.xml : <?xml version="1.0" encoding="UTF-8"?> <Test >
3
by: tarawa | last post by:
Hey Guys, I'm not sure if this is valid or not, but I was asked to create a schema which in it has a complex type, this complex type has two or more elements where each one of them has different...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.