10

xmlを読み込もうとすると、「予期しないXML宣言。XML宣言はドキュメントの最初のノードである必要があり、その前に空白文字を表示することはできません」というエラーが表示されます。私のC#コードとXMLファイルの内容の両方を以下に示します。XML定義がxmlファイルの6行目に存在するため、エラーが発生します。

xmlファイルの内容を制御できないので、C#を使用して編集/書き換えて、xml宣言が最初に来て、次にコメントがエラーなしでロードされるようにするにはどうすればよいですか?

//xmlFilepath is the path/name of the xml file passed to this function
static function(string xmlFilepath)
{
XmlReaderSettings readerSettings = new XmlReaderSettings();
readerSettings.IgnoreComments = true;
readerSettings.IgnoreWhitespace = true;
XmlReader reader = XmlReader.Create(XmlFilePath, readerSettings);
XmlDocument xml = new XmlDocument();
xml.Load(reader);
}

XmlDoc.xml

<!-- Customer ID: 1 -->
<!-- Import file: XmlDoc.xml -->
<!-- Start time: 8/14/12 3:15 AM -->
<!-- End time: 8/14/12 3:18 AM -->

<?xml version="1.0" encoding="ISO-8859-1" standalone="yes"?>
-----
4

4 に答える 4

17

エラーが示すように、XMLドキュメントの最初の5文字は。である必要があります<?xml。ifs、ands、butsはありません。開始XMLタグの上にあるコメントは違法です。それらはXMLタグの内側に配置する必要があります(コメント構造自体がXML標準によって定義されているため、メインのXMLタグの外側では意味がないため)。

編集: OPからのファイル形式を考えると、このようなもので行を再配置できるはずです:

var lines = new List<string>();

using (var fileStream = File.Open(xmlFilePath, FileMode.Open, FileAccess.Read))
   using(var reader = new TextReader(fileStream))
   {
      string line;
      while((line = reader.ReadLine()) != null)
         lines.Add(line);
   }   

var i = lines.FindIndex(s=>s.StartsWith("<?xml"));
var xmlLine = lines[i];
lines.RemoveAt(i);
lines.Insert(0,xmlLine);

using (var fileStream = File.Open(xmlFilePath, FileMode.Truncate, FileAccess.Write)
   using(var writer = new TextWriter(fileStream))
   {
      foreach(var line in lines)
         writer.Write(line);

      writer.Flush();
   } 
于 2012-08-14T19:26:16.323 に答える
5

これは有効なXMLではありません。

エラーが明確に示しているように、XML宣言(<?xml ... ?>)が最初に来る必要があります。

于 2012-08-14T19:23:55.377 に答える
1

次の関数を使用して、xmlから空白を削除しています。

public static void DoRemovespace(string strFile)
    {
        string str = System.IO.File.ReadAllText(strFile);
        str = str.Replace("\n", "");
        str = str.Replace("\r", "");
        Regex regex = new Regex(@">\s*<");
        string cleanedXml = regex.Replace(str, "><");
        System.IO.File.WriteAllText(strFile, cleanedXml);

    }
于 2015-02-12T11:58:43.703 に答える
1

ファイルの先頭にコメントを入れないでください。

于 2017-04-14T02:33:56.613 に答える