首页 > 解决方案 > 如何将每个键的多个值写入 XML 文件?

问题描述

我有一个简单的 XML 文件:

<?xml version="1.0" encoding="utf-16"?>
<dictionary>
  <Item>
    <Key>
      <string>Stations</string>
    </Key>
    <Value>
      <string>Station 1</string>
    </Value>
  </Item>
  <Item>
    <Key>
      <string>Vendors</string>
    </Key>
    <Value>
      <string>Vendor 1</string>
    </Value>
  </Item>
</dictionary>

所以我想为每个键保存多个值。在此示例中,我将添加供应商 2 或类似的东西。我需要能够存储多个站点、多个供应商,但我不知道如何在 XML 中执行此操作。我在我的 C# 应用程序中使用它来读取不时更改的数据,因此我无法对其进行硬编码。我只是希望每个键都能拥有一个“列表”。这可能吗?

标签: xmldictionarykey

解决方案


你可以有一个像这样的 XML:

<?xml version="1.0" encoding="utf-16"?>
<dictionary>
  <Item>
    <Key>
      <string>Stations</string>
    </Key>
    <Value>
      <string>Station 1</string>
      <string>Station 2</string>
    </Value>
  </Item>
  <Item>
    <Key>
      <string>Vendors</string>
    </Key>
    <Value>
      <string>Vendor 1</string>
      <string>Vendor 2</string>
      <string>Vendor 3</string>
    </Value>
  </Item>
</dictionary>

您可以使用XMLNode.ChildNodes访问值列表


推荐阅读