用于替换节点属性内容的正则表达式
我有一个如下所示的 xml 文档:
如何仅在属性中将“employee”替换为“supervisor”并将“manager”替换为“employee”?
谢谢, 克
I have an xml document like the following:
<nodes> <node idName="employee">Some Text Here "employee" idName="employee" employee<innderNode idName="manager">Some Manager Text Here manager manager "manager" </innerNode> </node> </nodes>
How do I replace "employee" with "supervisor" and replace "manager" with "employee" ONLY in the attributes?
Thanks,
g
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
正则表达式无法处理 XML 所属的语言类别。不过,当然有一种很巧妙的方法可以做到这一点:
idName="something"
- 包括等号和引号 - 并将其替换为idName="somethingelse"
但是,这当然仅在上面显示的确切字符串肯定不会作为文本显示在任何 XML 元素主体中时才有效。如果是这种情况,那么确实没有办法找到合适的 XML 解析器。
尽管现代正则表达式通常可以处理比常规语言更多的内容,但它们只能处理这么多。您将需要上下文无关语法来解析 XML。
A regex is not able to handle the class of languages an XML is part of. However there is of course a hacky way to do this:
idName="something"
- including the equals sign and the quotes - and replace it withidName="somethingelse"
However, this of course only works when the exact string as shown above is certain not to show up in any XML element body as text. If this is the case, there is really no way that leads around a proper XML parser.
Although modern regexes can often handle more than regular languages, the can only handle so much. You will need a context free grammar to parse XML.
我同意,在理想的情况下,您应该使用适当的 XML 解析器。
然而,世界并不理想,如果您需要,正则表达式可以处理这个问题。
这是一个与 perl/sed 一起使用的示例,它应该很容易转换为任何语言:
这可以很容易地修改为包含其他属性,它看起来像这样:
等等,注意它变得饥饿如果 XML 包含大块,则占用内存。
I agree that you should, in an ideal world, be using a proper XML parser.
However, the world isn't ideal, and regexes can handle this if you need them to.
Here is an example which will work with perl/sed, it should be easy to convert to any lang:
This could easily be modified to include other attributes, it would look somthing like this:
And so on, watch out for it getting hungry for memory if the XML contains large chunks though.