如何修复 XML“开始和结束标记不匹配错误"? [英] How to fix XML "Opening and ending tag mismatch error"?

查看:150
本文介绍了如何修复 XML“开始和结束标记不匹配错误"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试修复一个包含数千行错误的 XML 文件:

I'm trying to fix an XML file with thousands of lines that have the error:

开始和结束标记不匹配错误

Opening and ending tag mismatch error

我现在使用 simpleXML 来解析这个文件,所以在用这个库解析之前我需要修复 XML 文件:

I'm using right now simpleXML to parse this file, so before parse with this librarie I need to fix the XML file:

现在我正在尝试这个解决方案,但这还不够:

Right now I'm trying with this solution but it's not enough:

libxml_use_internal_errors(true);
$xml = @simplexml_load_file($temp_name);
     $errors = libxml_get_errors();
     foreach ($errors as $error) {
         if (strpos($error->message, 'Opening and ending tag mismatch')!==false) {
             $tag   = trim(preg_replace('/Opening and ending tag mismatch: (.*) line.*/', '$1', $error->message));
             $lines = file($temp_name, FILE_IGNORE_NEW_LINES);
             $line  = $error->line+1;
             echo $line;
             echo "<br>";
             $lines[$line] = '</'.$tag.'>'.$lines[$line];
             file_put_contents($temp_name, implode("\n", $lines));
         }
     }

有什么想法吗?

推荐答案

首先,如果您有损坏的数据,那么修复生成它的程序通常比修复数据更重要.

First, if you've got corrupt data then fixing the program that generated it is usually more important than repairing the data.

如果文件中唯一的错误是不匹配的结束标记,那么修复策略可能是完全忽略结束标记中的内容,因为出现在 XML 结束标记中的名称是多余的.您可能会发现现有的工具(例如 TagSoup 或 validator.nu)会以您想要的方式处理此问题;或者您可能会发现这样的工具输出的 XML 可以转换为您想要的形式.这比为这种非 XML 语法编写自己的解析器更好.

If the only errors in the file are mismatched end tags, then presumably the repair strategy is to ignore what's in the end tag entirely, given that the name appearing in an XML end tag is redundant. You might find that an existing tool such as TagSoup or validator.nu handles this the way you want; or you might find that such a tool outputs XML which can be transformed into the form you want. That's a better prospect than writing your own parser for this non-XML grammar.

这篇关于如何修复 XML“开始和结束标记不匹配错误"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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