我在我开发的程序中使用XML文件。
当我在另一台机器上安装程序时,出现以下错误:
"XML document must have a top level element".
通过WordPad检查XML内容,发现安装过程中XML内容已损坏且每个'<'字符被替换为'>'一个,反之亦然。
这是输出:
?>xml version="1.0" encoding="windows-1252<?"
如何通过代码检查这样的事情,如何替换错误的字符?
谢谢!
答案 0 :(得分:1)
这是一个如何基于我的评论来修复它的示例
using System;
namespace replace
{
internal class Program
{
private static void Main(string[] args)
{
var damaged = ">?xml version='1.0' encoding='windows-1252'?<"
+ ">level1<"
+ ">level2<"
+ ">level3<"
+ ">Object Value='TEST'<"
+ ">/level3<"
+ ">/level2<"
+ ">/level1<"
+ ">/XML<";
Console.WriteLine("Default:");
Console.WriteLine(damaged);
damaged = damaged.Replace("<>", "><");
Console.WriteLine("Step1:");
Console.WriteLine(damaged);
damaged = damaged.ReplaceAt(0, '<');
var Fixed = damaged.ReplaceAt(damaged.Length - 1, '>');
Console.WriteLine("Step2:");
Console.WriteLine(Fixed);
Console.Read();
}
}
public static class Extension
{
public static string ReplaceAt(this string input, int index, char newChar)
{
if (input == null)
{
throw new ArgumentNullException("input");
}
char[] chars = input.ToCharArray();
chars[index] = newChar;
return new string(chars);
}
}
}