如何将具有多个值的xml字段添加到字典中

  • 本文关键字:字段 xml 添加 字典 c# xml
  • 更新时间 :
  • 英文 :


我写了一个C#代码,可以将xml字段及其值转换为字典,但我没有注意到的是,我收到的xml文件中有一些字段包含多个值(ConditionAncestorTerm(,如下一块所示:

<StudyFieldsResponse>
<APIVrs>1.01.02</APIVrs>
<DataVrs>2020:12:06 23:30:13.949</DataVrs>
<Expression>ca045-011</Expression>
<NStudiesAvail>359831</NStudiesAvail>
<NStudiesFound>1</NStudiesFound>
<MinRank>1</MinRank>
<MaxRank>20</MaxRank>
<NStudiesReturned>1</NStudiesReturned>
<FieldList>
<Field>CompletionDate</Field>
<Field>Condition</Field>
<Field>ConditionAncestorTerm</Field>
</FieldList>
<StudyFieldsList>
<StudyFields Rank="1">
<FieldValues Field="CompletionDate">
<FieldValue>January 17, 2026</FieldValue>
</FieldValues>
<FieldValues Field="Condition">
<FieldValue>Renal Cell Carcinoma</FieldValue>
</FieldValues>
<FieldValues Field="ConditionAncestorTerm">
<FieldValue>Neoplasms, Glandular and Epithelial</FieldValue>
<FieldValue>Neoplasms by Histologic Type</FieldValue>
<FieldValue>Neoplasms</FieldValue>
<FieldValue>Adenocarcinoma</FieldValue>
<FieldValue>Kidney Neoplasms</FieldValue>
<FieldValue>Urologic Neoplasms</FieldValue>
<FieldValue>Urogenital Neoplasms</FieldValue>
<FieldValue>Neoplasms by Site</FieldValue>
<FieldValue>Kidney Diseases</FieldValue>
<FieldValue>Urologic Diseases</FieldValue>
</FieldValues>

我将XML元素转换为字典的C#代码最初看起来是这样的:

static Dictionary<string, string> DecodeXML(XDocument study)
{
// Convert XML to a dictionary
var data = study
.Elements("StudyFieldsResponse")
.Elements("StudyFieldsList")
.Elements("StudyFields")
.Elements("FieldValues")
.ToDictionary(
key => key.Attribute("Field").Value,
value => value.Element("FieldValue").Value
);
return data;
}

我的代码现在坏了,因为有些字段有多个值,我猜程序处理得不太好。我希望能够将与一个字段对应的所有值添加到列表中,所以我想我应该将字典更改为<字符串,列表>以使其工作,但我还没有找到将每个值存储到列表中的方法。有人知道我该怎么做吗?

尝试以下操作:

XDocument doc = XDocument.Load(FILENAME);
Dictionary<string, XElement> dict = doc.Descendants("FieldValues")
.GroupBy(x => (string)x.Attribute("Field"), y => y)
.ToDictionary(x => x.Key, y => y.FirstOrDefault());

或者这个

XDocument doc = XDocument.Load(FILENAME);
Dictionary<string, List<string>> dict = doc.Descendants("FieldValues")
.GroupBy(x => (string)x.Attribute("Field"), y => y)
.ToDictionary(x => x.Key, y => y.Elements("FieldValue").Select(z => (string)z).ToList());

首先加载xml,然后创建字典

`

var xml= XDocument.Load("XMLFileName.xml");
var data= xml.Document.Root.Elements("StudyFieldsResponse")
.Elements("StudyFieldsList")
.Elements("StudyFields")
.Elements("FieldValues")
.ToDictionary(
x => x.Attribute("Field").Value,
x => x.Elements("FieldValue")
.Select(y => y.Value)
.ToArray());

`

如果您共享要显示的输出,会更有帮助。

最新更新