我正在嘗試使用 加載 XML 檔案XDocument.Load(stream),但有些檔案被宣告為
#<?xml version="1.0" encoding="utf-16"?>
<root>
</root>
由于開始#,我收到了XmLException一條訊息
根級別的資料無效。第 1 行,位置 1。
為了處理這個例外,我有這個后備想法:
XDocument? xDoc = null;
var fileName = "C:\dummy.xml";
try
{
await using var fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
xDoc = await XDocument.LoadAsync(fileStream, LoadOptions.None, CancellationToken.None).ConfigureAwait(false);
}
catch (Exception e)
{
//my idea would be, if an exception occured
//- read the file into memory
//- verify if it starts with '#'
//- drop the '#'
}
有沒有更好的方法來處理檔案#?
是#我不知道的一些 XML 規范嗎?
uj5u.com熱心網友回復:
我可能會事先經歷一個單獨的階段,在適當的情況下復制沒有第一個位元組的檔案。例如:
foreach (var file in Directory.GetFiles("*.xml"))
{
// Note: this assumes all XML files are UTF-8.
using (var input = File.OpenRead(file))
{
int firstByte = input.ReadByte();
if (firstByte != '#')
{
continue;
}
string tmp = file "-tmp";
using (var copy = File.Create(tmp))
{
input.CopyTo(copy);
}
// Close the stream so we can rename.
input.Close();
// Move the original file to a backup, and the temporary to the original name
File.Move(file, Path.ChangeExtension(file, ".bak"));
File.Move(tmp, file);
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/512780.html
標籤:C#xml
