由于您添加了更多详细信息,我现在可以提供更好的答案。这是一个功能性的 xml 解析和加入控制台应用程序,它演示了您正在寻找的内容(我认为)。要解析 xml 文件而不是 xml 字符串,请使用XDocument
Load 方法而不是显示的 Parse 方法。祝你好运,
XDocument docA = XDocument.Parse(
@"<Devanagri_to_itrans>
<mapping>
<character>अ</character>
<itrans>a</itrans>
</mapping>
</Devanagri_to_itrans>");
XDocument docB = XDocument.Parse(
@"<Gujrathi_to_itrans>
<mapping>
<character>અ</character>
<itrans>a</itrans>
</mapping>
</Gujrathi_to_itrans>");
var devanagriKeys = (from d in docA.Descendants("mapping")
select new {
Key = d.Descendants("itrans").FirstOrDefault().Value,
Character = d.Descendants("character").FirstOrDefault().Value
}).ToArray();
var gujrathiKeys = (from g in docB.Descendants("mapping")
select new {
Key = g.Descendants("itrans").FirstOrDefault().Value,
Character = g.Descendants("character").FirstOrDefault().Value
}).ToArray();
var crossReference = (from d in devanagriKeys
join g in gujrathiKeys on d.Key equals g.Key
select new {
d.Key,
Devanagri = d.Character,
Gujrathi = g.Character
}).ToList();
Console.WriteLine("Enter a key character to translate:");
string searchKey = Console.ReadLine();
var translation = crossReference.Where(cr => cr.Key == searchKey).FirstOrDefault();
if (translation == null)
Console.WriteLine("No such key in the cross reference.");
else
Console.WriteLine("{0} is {1} in Devanagri and {2} in Gujrathi",
translation.Key, translation.Devanagri, translation.Gujrathi);
Console.ReadKey(true);
根据会话变量的请求:
匿名类型仅用于方法中。要将列表放入 Session 变量以在其他地方使用,请创建一个您自己的真实类,其中包含 3 个所需的属性,并将上面的代码行更改为与下面的非常匹配。(我选择的班级名称是CrossReferenceTranslation
。)
Session["CrossReference"] = (from d in devanagriKeys
join g in gujrathiKeys on d.Key equals g.Key
select new CrossReferenceTranslation() {
d.Key,
Devanagri = d.Character,
Gujrathi = g.Character
}).ToList();
...然后,在其他某个时间点,您可以执行此操作以将会话对象列表放入变量中。请注意变量可能为空的假设,只要会话超时就会发生这种情况......
List<CrossReferenceTranslation>() crossReference = Session["CrossReference"] ??
new List<CrossReferenceTranslation>();