C# 转换字典<;字符串,字符串>;“通过异常转换为xml”;名称不能以';1';字符,十六进制值0x31&引用;

C# 转换字典<;字符串,字符串>;“通过异常转换为xml”;名称不能以';1';字符,十六进制值0x31&引用;,c#,xml,linq,dictionary,xelement,C#,Xml,Linq,Dictionary,Xelement,下面是我试图将字典转换为xml字符串的代码 XElement xml_code = new XElement("root", myDictionary.Select(item => new XElement(item.Key, item.Value))); 上面的代码抛出错误 名称不能以“1”字符(十六进制值0x31)开头 字典快照 发生这种情况可能是因为词典中的一个或多个条目违反了xml命名约定 示例: 在这里,我再现了你们面临的问题 考虑一下这个源代码 static void Mai

下面是我试图将字典转换为xml字符串的代码

XElement xml_code = new XElement("root", myDictionary.Select(item => new XElement(item.Key, item.Value)));
上面的代码抛出错误

名称不能以“1”字符(十六进制值0x31)开头

字典快照


发生这种情况可能是因为词典中的一个或多个条目违反了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();
}
对于这段代码,我得到了以下异常

名称不能以“1”字符(十六进制值0x31)开头

说明: 正如您在第一个代码中所看到的,字典的键条目只包含字母表。在本例中,我们得到一个适当的输出,该输出由xml形式的字典条目组成。而在第二段代码中,我做了一点小小的更改,将键条目
“vegtable”
作为
“1vegtable”
启动,我们得到了一个异常

此问题的原因在于Xml命名约定,根据该约定,Xml节点的名称不能以数值开头。因为字典的键值存储为Xml节点,所以我们得到了异常。源代码也是如此

有关更多信息,请阅读以下帖子:


@Steve谢谢,我正在尝试将字典转换为xml,然后将其作为参数传递给存储过程。现在我知道了错误原因。有没有其他方法可以将字典传递给存储过程?您可以探索这个选项
<root>
      <Fruit>Apple</Fruit>
      <Vegtable>Potato</Vegtable>
      <Vehicle>Car</Vehicle>
</root>
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();
}