Remove Namespace for XML Document
You can remove unwanted namespaces in an XML Document by using Regex
public static string RemoveDocumentNamespace(string XMLData)
{
XmlDocument _currentXMLDocument = new XmlDocument();
_currentXMLDocument.LoadXml(XMLData);
XmlDocument _convertedDocument = new XmlDocument();
_convertedDocument.LoadXml(System.Text.RegularExpressions.Regex.Replace(
_currentXMLDocument.OuterXml, @"(xmlns:?[^=]*=[""][^""]*[""])", "",
System.Text.RegularExpressions.RegexOptions.IgnoreCase | System.Text.RegularExpressions.RegexOptions.Multiline)
);
return _convertedDocument.InnerXml;
}
The above example can be used if your .Net Framework is <= 3.0
if it is > 3.0 then you can use a LINQ method to remove Namespaces.
This can be used in Silverlight Application
public static XDocument RemoveNamespace(XDocument xDocument)
{
foreach (XElement oElement in xDocument.Root.DescendantsAndSelf())
{
if (oElement.Name.Namespace != XNamespace.None)
{
oElement.Name = XNamespace.None.GetName(oElement.Name.LocalName);
}
if (oElement.Attributes().Where(a => a.IsNamespaceDeclaration || a.Name.Namespace != XNamespace.None).Any())
{
oElement.ReplaceAttributes(oElement.Attributes().Select(a => a.IsNamespaceDeclaration ? null : a.Name.Namespace != XNamespace.None ? new XAttribute(XNamespace.None.GetName(a.Name.LocalName), a.Value) : a));
}
}
return xDocument;
}
public static string RemoveDocumentNamespace(string XMLData)
{
XmlDocument _currentXMLDocument = new XmlDocument();
_currentXMLDocument.LoadXml(XMLData);
XmlDocument _convertedDocument = new XmlDocument();
_convertedDocument.LoadXml(System.Text.RegularExpressions.Regex.Replace(
_currentXMLDocument.OuterXml, @"(xmlns:?[^=]*=[""][^""]*[""])", "",
System.Text.RegularExpressions.RegexOptions.IgnoreCase | System.Text.RegularExpressions.RegexOptions.Multiline)
);
return _convertedDocument.InnerXml;
}
The above example can be used if your .Net Framework is <= 3.0
if it is > 3.0 then you can use a LINQ method to remove Namespaces.
This can be used in Silverlight Application
public static XDocument RemoveNamespace(XDocument xDocument)
{
foreach (XElement oElement in xDocument.Root.DescendantsAndSelf())
{
if (oElement.Name.Namespace != XNamespace.None)
{
oElement.Name = XNamespace.None.GetName(oElement.Name.LocalName);
}
if (oElement.Attributes().Where(a => a.IsNamespaceDeclaration || a.Name.Namespace != XNamespace.None).Any())
{
oElement.ReplaceAttributes(oElement.Attributes().Select(a => a.IsNamespaceDeclaration ? null : a.Name.Namespace != XNamespace.None ? new XAttribute(XNamespace.None.GetName(a.Name.LocalName), a.Value) : a));
}
}
return xDocument;
}
Thanks, just what I needed!
ReplyDeletethank you, helped me alot!
ReplyDelete