RegEx关闭未关闭的标签

时间:2010-12-20 20:54:44

标签: c# regex

我从投票提供商处收到了一些无效的XML数据,并希望在处理之前清理几个未关闭的标签。

目前的数据如下:

<questions>
<question number="1">
<title>What is your name?</title>
<answer>John Doe<answer> <!-- this is the problem -->
</question>
<question number="2">
...
</question>

有没有办法用正则表达式来清理它并继续关闭<answer>标记?

我有这个:"<answer>.*?(?<closingtag><answer>)"来查找事件,但如何在<closingtag>命名组上进行特定替换?

对于这个非常基本的问题感到抱歉,但我正在用我的正则表达式进行一些努力。

谢谢,

哈尔

2 个答案:

答案 0 :(得分:2)

如果问题总是丢失/(也就是说 匹配的标签,但它当前不是关闭),你可以这样做:

查找:<([^/>]+)>([^<]*?)<\1>

替换为:<\1>\2</\1>

这将尝试查找标记为两行的未封闭标记(不包括自动关闭标记),并将其替换为标记,内容,然后是标记的结束版本。 / p>

当然有一些警告 - 如果标签的属性包含/,或者未关闭标签的值包含<(或其他标签),则此正则表达式不会工作

答案 1 :(得分:2)

在XML验证中编程修复人为错误是一件麻烦事。在极端情况下,您也可以撤消所有XML验证。举一个例子:

<questions> 
<question number="1"> 
<title>What is your name?</title> 
<answer>John Doe<answer> 
<!-- this is the problem --> </question> <question number="2"> ... </question>

...修复

<answer>John Doe</answer> 

或者...

<answer>John</answer><answer> Doe</answer>

或者...

<answer>John Doe</answer><answer> </answer>

你能看到这是怎么回事吗?

相关问题