我将一些遗留的XML文档存储在数据库中作为blob,它们不是格式良好的XML。我正在从SQL数据库中读取它们,最终,当我使用C#.NET时,希望将它们实例化为XMLDocument。
当我尝试这样做时,我显然得到了一个XMLException。看过XML文档之后,由于特定XML节点中未声明的命名空间,它们都失败了。
我不关心任何具有此前缀的XML节点,因此我可以忽略它们或将它们丢弃。基本上,在我将字符串作为XMLDocument加载之前,我想删除字符串中的前缀,以便
<tem:GetRouteID>
<tem:PostCode>postcode</tem:PostCode>
<tem:Type>ItemType</tem:Type>
</tem:GetRouteID>
变为
<GetRouteID>
<PostCode>postcode</PostCode>
<Type>ItemType</Type>
</GetRouteID>
和这个
<wsse:Security soapenv:actor="">
<wsse:BinarySecurityToken>token</wsse:BinarySecurityToken>
</wsse:Security>
成为这个:
<Security soapenv:actor="">
<BinarySecurityToken>token</BinarySecurityToken>
</Security>
我有一个解决方案可以这样做:
<appSettings>
<add key="STRIP_NAMESPACES" value="wsse;tem" />
</appSettings>
if (STRIP_NAMESPACES != null)
{
string[] namespaces = Regex.Split(STRIP_NAMESPACES, ";");
foreach (string ns in namespaces)
{
str2 = str2.Replace("<" + ns + ":", "<"); // Replace opening tag
str2 = str2.Replace("</" + ns + ":", "</"); // Replace closing tag
}
}
但理想情况下我想要一个通用的方法,所以我不必无休止地配置我想删除的命名空间。
如何在C#.NET中实现这一目标。我假设一个正则表达式是去这里的方式?
更新1
Ria的正则表达式适用于上述要求。但是,我如何更改正则表达式以更改此
<wsse:Security soapenv:actor="">
<BinarySecurityToken>authtoken</BinarySecurityToken>
</Security>
到此?
<Security>
<BinarySecurityToken>authtoken</BinarySecurityToken>
</Security>
更新2
认为我已根据Ria的答案自行制定了更新版本:
<(/?)\w+:(\w+/?) ?(\w+:\w+.*)?>
答案 0 :(得分:6)
<强>更新强>
对于新问题(attribs命名空间),请尝试此常规解决方案。这对节点值没有影响:
Regex.Replace(originalXml,
@"((?<=</?)\w+:(?<elem>\w+)|\w+:(?<elem>\w+)(?==\"))",
"${elem}");
在我的示例xml上试试这个正则表达式:
<wsse:Security soapenv:actor="dont match soapenv:actor attrib">
<BinarySecurityToken>authtoken</BinarySecurityToken>
</Security>
尝试使用XSL
,您可以直接应用XSL
或在.NET中使用XslTransform
类:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="no"/>
<xsl:template match="/|comment()|processing-instruction()">
<xsl:copy>
<xsl:apply-templates/>
</xsl:copy>
</xsl:template>
<xsl:template match="*">
<xsl:element name="{local-name()}">
<xsl:apply-templates select="@*|node()"/>
</xsl:element>
</xsl:template>
<xsl:template match="@*">
<xsl:attribute name="{local-name()}">
<xsl:value-of select="."/>
</xsl:attribute>
</xsl:template>
</xsl:stylesheet>
或尝试此Regex
:
var finalXml = Regex.Replace(originalXml, @"<(/?)\w+:(\w+/?)>", "<$1$2>");