这可能是因为您的字典中的一个或多个条目违反了 xml 命名约定。
示例:
在这里,我已经重现了您面临的问题。
考虑这个源代码
static void Main(string[] args)
{
Dictionary<string, string> myList = new Dictionary<string, string>();
myList.Add("Fruit", "Apple");
myList.Add("Vegtable", "Potato");
myList.Add("Vehicle", "Car");
XElement ele = new XElement("root", myList.Select(kv => new XElement(kv.Key, kv.Value)));
Console.WriteLine(ele);
Console.Read();
}
你会得到输出
<root>
<Fruit>Apple</Fruit>
<Vegtable>Potato</Vegtable>
<Vehicle>Car</Vehicle>
</root>
现在让我们修改代码,将数字值放在字典条目中键值的开头,即将"vegtable"写成"1vegtable"
static void Main(string[] args)
{
Dictionary<string, string> myList = new Dictionary<string, string>();
myList.Add("Fruit", "Apple");
//Inserting 1 before vegtable
myList.Add("1Vegtable", "Potato");
myList.Add("Vehicle", "Car");
XElement ele = new XElement("root", myList.Select(kv => new XElement(kv.Key, kv.Value)));
Console.WriteLine(ele);
Console.Read();
}
对于这段代码,我得到了以下异常
名称不能以“1”字符开头,十六进制值 0x31。
解释:
正如您在字典的第一个代码中看到的那样,键条目仅包含字母。在这种情况下,我们得到了一个正确的输出,其中包含作为 xml 的字典条目。而在第二个代码中,我通过将密钥条目 "vegtable" 启动为 "1vegtable" 进行了轻微更改,但我们遇到了异常。
此问题的原因在于 Xml 命名约定,根据该约定,Xml 节点的名称不能以数值开头。由于字典的键值存储为 Xml 节点,因此我们遇到了异常。您的源代码也是如此。
更多信息请阅读以下帖子:
Name cannot begin with the '1' character, hexadecimal value 0x31. Line 2, position 2
Xml Standards