Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
378 views
in Technique[技术] by (71.8m points)

c# - How can I add closed tag in xml document?

I have next problem: I created downloader, which downloads xml documents, but in one the document has problem, in the document not end tag. For example:

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

I have next code:

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;
        }

    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Document containing unclosed tag is not XML at all. As others suggested in comments, ideally the effort to fix this problem is done by the party that generate the document.

Regarding the original question, detecting unclosed tag in general isn't a trivial task. I would suggest to try HtmlAgilityPack (HAP). It has built in functionality to automatically close unclosed tags (closing tag added immediately after the opening tag).

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);

output :

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...