【问题标题】:Convert Dictionary<string, string> to xml through exception "Name cannot begin with the '1' character, hexadecimal value 0x31. " [duplicate]通过异常“名称不能以'1'字符开头,十六进制值0x31。”将Dictionary<string,string>转换为xml。 [重复]
【发布时间】:2019-07-09 06:59:41
【问题描述】:

这是我尝试将 Dictionary 转换为 xml 字符串的代码。

XElement xml_code = new XElement("root", myDictionary.Select(item => new XElement(item.Key, item.Value)));

上面的代码抛出错误

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

字典快照

【问题讨论】:

标签: c# xml linq dictionary xelement


【解决方案1】:

这可能是因为您的字典中的一个或多个条目违反了 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

【讨论】:

    猜你喜欢
    • 2012-05-17
    • 2021-06-26
    • 2019-10-25
    • 2017-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-30
    • 2018-08-09
    相关资源
    最近更新 更多