删除XML中的名称空间 [英] Removing namespaces in XMLs

查看:101
本文介绍了删除XML中的名称空间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,

我需要从xml文件中删除所有名称空间.我正在使用功能

Hi All,

I need to remove all namespaces from an xml file. I am using the functions

public static string RemoveAllNamespaces(string xmlDocument)
{
   XElement xmlDocumentWithoutNs = RemoveAllNamespaces(XElement.Parse(xmlDocument));
   return xmlDocumentWithoutNs.ToString();
}

private static XElement RemoveAllNamespaces(XElement xmlDocument)
{
   if (!xmlDocument.HasElements)
   {
    XElement xElement = new XElement(xmlDocument.Name.LocalName);
    xElement.Value = xmlDocument.Value;
    foreach (XAttribute attribute in xmlDocument.Attributes())
    xElement.Add(attribute);
    return xElement;
   }
   return new XElement(xmlDocument.Name.LocalName, xmlDocument.Elements().Select(el => RemoveAllNamespaces(el)));
}



问题是我正在通过其中一个函数返回以下错误



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.PushNamespaceExplicit(String prefix, String ns)
   at System.Xml.XmlWellFormedWriter.WriteEndAttribute()
   at System.Xml.Linq.ElementWriter.WriteStartElement(XElement e)
   at System.Xml.Linq.ElementWriter.WriteElement(XElement e)
   at System.Xml.Linq.XElement.WriteTo(XmlWriter writer)
   at System.Xml.Linq.XNode.GetXmlString(SaveOptions o)
   at System.Xml.Linq.XNode.ToString()



有人可以在xml文件中删除名称空间的另一种方法吗?

非常感谢

烧杯

[edit]已添加代码块-OriginalGriff [/edit]



Can somebody thing of an alternative way of removing namespaces within an xml file?

Many thanks

bekets

[edit]Code block added - OriginalGriff[/edit]

推荐答案



在这里看看:
http://msdn.microsoft.com/zh-cn/library/system.xml.xmlnamespacemanager.removenamespace%28v = vs.95%29.aspx [
Hi,

Have a look here:
http://msdn.microsoft.com/en-us/library/system.xml.xmlnamespacemanager.removenamespace%28v=vs.95%29.aspx[^]


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



将删除所有名称空间.感谢ProgramFox提供的指针



will remove all namespaces. Thanks ProgramFox for the pointer


这篇关于删除XML中的名称空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆