C# XML和哈希表
我有以下XML文件:C# XML和哈希表,c#,xml,c#-4.0,c#-3.0,hashtable,C#,Xml,C# 4.0,C# 3.0,Hashtable,我有以下XML文件: <states> <state> <Name>a1</Name> <Address>a2</Address> <Name>b1</Name> <Address>b2</Address> <Name>c1</Name>
<states>
<state>
<Name>a1</Name>
<Address>a2</Address>
<Name>b1</Name>
<Address>b2</Address>
<Name>c1</Name>
<Address>c2</Address>
</state>
<state>
<Name>aa1</Name>
<Address>aa2</Address>
<Name>bb1</Name>
<Address>bb2</Address>
</state>
</states>
a1
a2
b1
b2
c1
c2
aa1
aa2
bb1
bb2
我需要将其存储在哈希表中,并使用C#从中检索值
有人能帮我吗?我同意乔恩·斯基特的观点。将属于同一个人的信息包装在一个单一实体中(比如说,
实体),这将是一种更好的结构化方法。你也应该给每个州一些名字或身份证;否则,您的分组将显示为任意分组
<states>
<state Name="Florida">
<Person Name="a1">
<Address>a2</Address>
</Person>
<Person Name="b1">
<Address>b2</Address>
</Person>
<Person Name="c1">
<Address>c2</Address>
</Person>
</state>
<state Name="New York">
<Person Name="aa1">
<Address>aa2</Address>
</Person>
<Person Name="bb1">
<Address>bb2</Address>
</Person>
</state>
</states>
也就是说,如果您经常需要更改密钥,
字典
可能不是最好的结构。您是否面临任何问题,或者您没有尝试过任何方法?XML文件是否必须这样组织?依赖于“名称后的第一个地址元素是该名称的地址”这样的顺序特定性并不是很好。你说的是C#3.0和C#4.0,但你想要一个哈希表。一般来说,请查看System.Collections.Generic.Dictionary。HashTable和ArrayList在2.0+版本中已经非官方地过时了。在他的辩护中,他可能将HashTable
与仍然流行的HashSet
混淆了。谢谢你的回答。这对我帮助很大。我是C#新手,所以这对我来说有点问题。道格拉斯,这是一些非常严格的代码。通常我会将所有内容都留在XML文档中,并将XPath与SelectSingleNode(“/states/state[@name='Florida']]/person[@name='a1']”一起使用,但这种IDictionary代码也是一种非常酷的方法。@Douglas,有没有办法在字典中编辑某人的名字,比如aa1?谢谢William!(尽管这个建议实际上是Krishh的。)如果你需要快速执行大量查找,字典是有利的。根据MSDN:“使用其键检索值非常快,接近O(1),因为字典类是作为哈希表实现的。”Krishh:我在帖子中回答。
XDocument document = XDocument.Parse(@"
<states>
<state Name=""Florida"">
<Person Name=""a1"">
<Address>a2</Address>
</Person>
<Person Name=""b1"">
<Address>b2</Address>
</Person>
<Person Name=""c1"">
<Address>c2</Address>
</Person>
</state>
<state Name=""New York"">
<Person Name=""aa1"">
<Address>aa2</Address>
</Person>
<Person Name=""bb1"">
<Address>bb2</Address>
</Person>
</state>
</states>");
IDictionary<string, Dictionary<string, string>> dictionary =
document.Root.Elements("state").ToDictionary(
state => state.Attribute("Name").Value,
state => state.Elements("Person").ToDictionary(
person => person.Attribute("Name").Value,
person => person.Element("Address").Value));
// To get address of "a1" living in Florida:
string addr1 = dictionary["Florida"]["a1"]; // gives "a2"
// To get address of "bb1" living in New York:
string addr2 = dictionary["New York"]["bb1"]; // gives "bb2"
Dictionary<string, string> innerDictionary = dictionary["New York"];
string address = innerDictionary["aa1"];
innerDictionary.Remove("aa1");
innerDictionary.Add("xx1", address);