如何在 xml 文档中添加闭合标签?

How can I add closed tag in xml document?

我有下一个问题:我创建了下载器,它下载 xml 个文件,但其中一个文件有问题,文件没有结束标记。例如:

<?xml version="1.0"?>
<rows xmlns:fo="http://www.w3.org/1999/XSL/Format">
<row StateID="AK">

我有下一个代码:

public void SaveFiles(SftpClient sftp, string DirectoryName, string PathToFile)
{
    foreach (Renci.SshNet.Sftp.SftpFile ftpfile in sftp.ListDirectory("." + DirectoryName))
    {
        DateTime downloadTime = ftpfile.LastWriteTime;
        string newFileName = ftpfile.Name;
        bool checkFile = check(PathToFile, newFileName, downloadTime);
        if (checkFile == true)
        {
            FileStream fs = new FileStream(PathToFile + "\" + ftpfile.Name, FileMode.Create);
            sftp.DownloadFile(ftpfile.FullName, fs);
            fs.Close();
            File.SetLastWriteTime(PathToFile + "\" + ftpfile.Name, downloadTime); 

        }
        else
        {
            continue;
        }

    }
}

包含未关闭标记的文档根本不是 XML。正如其他人在评论中所建议的那样,理想情况下,解决此问题的工作是由生成文档的一方完成的。

关于最初的问题,检测未闭合的标签通常不是一项简单的任务。我建议尝试 HtmlAgilityPack (HAP)。它具有自动关闭未关闭标签的内置功能(关闭标签紧跟在开始标签之后)。

example using HAP :

using HtmlAgilityPack;

......

var xml = @"<?xml version=""1.0""?>
<rows xmlns:fo=""http://www.w3.org/1999/XSL/Format"">
<row StateID=""AK"">";
var doc = new HtmlDocument();
doc.LoadHtml(xml);
Console.WriteLine(doc.DocumentNode.OuterHtml);

输出:

<?xml version="1.0"?>
<rows xmlns:fo="http://www.w3.org/1999/XSL/Format">
<row stateid="AK"></row></rows>