有时,我必须使用格式不正确的 xml(没有 root)。因此,我采用第一个节点名称(在本例中为“错误”)并组成正则表达式模式: "</error>$"
问题是它与以下字符串匹配 true。 ( </error>
是行尾)
<error>0</error>
<roles>
<role rid="12" title="User" description="Hello world"></role>
<role rid="11" title="Admin" description="Hello world2"></role></roles>
在查看了一些引用资料后,我尝试这样做</error>\z
和</error>\Z
。但它不起作用。
请帮我解决一下
附注如果有更好的解决方案,我会很高兴。目标环境是javascript。
最佳答案
如果导致 XML 格式不正确的唯一原因是它缺少根元素,那么修复方法很简单 – 只需添加一些根元素,然后解析它并像普通 XML 一样使用它。
xml = '<root>' + xml + '</root>';
You really shouldn't try to parse XML with regular expressions.
关于javascript - 正则表达式和xml,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6322070/