使用正则表达式从 XML 中删除命名空间引用 [英] Remove Namespace references from XML with Regex

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

问题描述

我有一个从 XML 中删除 xmlns 引用的正则表达式.当有匹配的标签时它工作正常,但如果 xmlns 引用在单个标签中,它也会删除/".

这是正则表达式:

"<(.*?) xmlns[:=].*?>", "<$1>"

当我在这行 xml 上使用正则表达式时:

<ns22:someTagName xmlns:ns22="http://exampledatatypes.com"></ns22:someTagName>

我得到了我想要的:

当我在这行 xml 上使用正则表达式时:

我得到这个无效的 XML:

它删除了引用罚款,但它需要关闭/".

感谢您的帮助,斯科特

解决方案

与其试图从 XML 中保留您需要的内容,不如针对您要删除的内容进行定位.

这个表达式只针对命名空间本身:

<块引用>

\sxmlns[^"]+"[^"]+"

不幸的是,我不知道 LotusScript,所以我不能给你一个如何使用它的代码示例,但你需要做的是像这样的伪代码:

result = regex.replace(yourString, '\sxmlns[^"]+"[^"]+"', '')

您在这里要做的是用空字符串替换所有匹配项(有效地删除它们).这对封闭和自封闭 XML 标签都适用,如果标签根本没有命名空间,它也适用.

这是一个功能齐全的 Python 示例:

<预><代码>>>>从重新导入子>>>模式 = r'\sxmlns[^"]+"[^"]+"'>>>关闭 = r'<ns22:someTagName xmlns:ns22="http://exampledatatypes.com"></ns22:someTagName>'>>>子(模式,'',关闭)'<ns22:someTagName></ns22:someTagName>'>>>selfclosed = r'<ns22:someTagName xmlns:ns22="http://exampledatatypes.com"/>'>>>子(模式,'',自闭)'<ns22:someTagName/>'

I have a regex that removes xmlns references from XML. It works fine when there are matching tags, but if the the xmlns reference is in a single tag it removes "/" as well.

Here is the regex:

"<(.*?) xmlns[:=].*?>", "<$1>"

When I use the regex on this line of xml:

<ns22:someTagName xmlns:ns22="http://exampledatatypes.com"></ns22:someTagName>

I get what I want:

<ns22:someTagName></ns22:someTagName>

When I use the regex on this line of xml:

<ns22:someTagName xmlns:ns22="http://exampledatatypes.com"/>

I get this invalid XML:

<ns22:someTagName>

It removes the reference fine, but it takes the closing "/" with it.

Thanks for the help, Scott

解决方案

Rather than trying to preserve what you need from the XML it would be better to target what you want to remove.

This expression targets just the namespace itself:

\sxmlns[^"]+"[^"]+"

Unfortunately I don't know LotusScript so I can't give you a code sample of how to use this but what you need to do is something like this psuedocode:

result = regex.replace(yourString, '\sxmlns[^"]+"[^"]+"', '')

What you will do here is replace all matches with an empty string (effectively removing them). This will work for both a closed and self-closed XML tag and it will also work if the tag doens't have a namespace at all.

Edit: Here is a fully-functional Python example:

>>> from re import sub
>>> pattern = r'\sxmlns[^"]+"[^"]+"'
>>> closed = r'<ns22:someTagName xmlns:ns22="http://exampledatatypes.com"></ns22:someTagName>'
>>> sub(pattern, '', closed)
'<ns22:someTagName></ns22:someTagName>'
>>> selfclosed = r'<ns22:someTagName xmlns:ns22="http://exampledatatypes.com"/>'
>>> sub(pattern, '', selfclosed)
'<ns22:someTagName/>'

这篇关于使用正则表达式从 XML 中删除命名空间引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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