【发布时间】:2010-10-20 02:44:00
【问题描述】:
我可以使用字典对象数组吗?
我有一个想要修改的 XML。我要使用的数据结构是这样的 -
Dictionary<element, Dictionary<attr, value>>
element - 是我要修改的元素 attr - 我要更新其值的属性 value - 我要更新的值
<Parents>
<Parent id="ParentA" description="New">
<Children>
<Child name="ChildA" />
</Children>
</Parent>
</Parents>
我想通过以下
Dictionary<string, string> dict_Attributes1=new Dictionary<string, string>();
Dictionary<string, string> dict_Attributes2=new Dictionary<string, string>();
dict_Attributes1.Add("id", "ParentB");
dict_Attributes1.Add("description", "Old");
dict_Attributes2.Add("name", "ChildB");
Dictionary<string, Dictionary<string, string>> dict_Elements = new Dictionary<string, Dictionary<string, string>>();
dict_Elements.Add(".", dict_Attributes1);//To update the Element
dict_Elements.Add("Children/Child", dict_Attributes2);//To update the Children's Attributes
假设我已经确定我要更新 id 为 ParentA 的 Parent。
现在,我在这里创建 dict_Attributes1、dict_Attributes2 等,有没有办法可以将它们存储在一个(动态,编译时大小未知)字典对象数组中?
或者,有没有更好的方法来做到这一点 - 1.修改Selected XElement及其子属性的属性?
编辑
<?xml version="1.0" encoding="utf-8"?>
<Configuration>
<Environments>
<Environment id="Master" description="MasterSystem">
<Systems>
<DefaultSystem systemName="Master" server="http://localhost" />
</Systems>
</Environment>
</Environments>
</Configuration>
现在,当用户更改 id 和描述时,我想用新值更新这个 XML 文件。在更改 id 和描述(从用户那里获得)时,我想用相同的 id 值更新 systemName。
如果新的id是“Development”,description是“DevelopmentSystem”,
输出的 XML 应该是
<?xml version="1.0" encoding="utf-8"?>
<Configuration>
<Environments>
<Environment id="Development" description="DeveloperSystem">
<Systems>
<DefaultSystem systemName="Development" server="http://localhost" />
</Systems>
</Environment>
</Environments>
</Configuration>
【问题讨论】:
-
只需使用
List<Dictionary<string, string>> -
@Kanini:有几件事 - 您可以使用 XSLT 来执行此操作,而不是尝试实现您自己的通用方式来指定应如何更新文件。除此之外,我建议专门编写代码来处理这种情况,而不是期望您的代码的用户构造一个带有选项路径的字典。更好的是,使用 XML 序列化,让他们编辑类的属性,而不是关心数据是如何存储的。
-
@Kanini:别误会,新值的 XPath 字典是一个有趣的选择,但是有更简单(编码和使用)且不易出错的编程方式这个。
-
@Kanini:使用 XSLT(如 Merlyn 所说)或 Linq-to-XML 会好得多
-
@Kanini:support.microsoft.com/kb/307322,w3schools.com/xsl。顺便说一句,w3schools 非常适合 HTML/XML 参考和教程 :)
标签: c# arrays dictionary