我有一个XML文件,其格式如下:
<datasources>
<datasource name="...">
<column caption="..." name="..."> ... </column>
<column caption="..." name="..."> ... </column>
</datasource>
<datasource name="...">
<column caption="..." name="..."> ... </column>
<column caption="..." name="..."> ... </column>
</datasource>
</datasources>
...
我希望获得符合特定条件的caption
name
地图(即预期为columns
并且为caption
预期的column
)。
目前我有这个代码,但我对它没有信心。
datasource
我担心的是,内部XmlReader reader = XmlReader.Create(new StringReader(content));
while (reader.ReadToFollowing("datasource"))
{
reader.MoveToAttribute("name");
if (reader.Value == dsName)
{
while (reader.ReadToFollowing("column"))
{
reader.MoveToAttribute("caption");
if (captions.Contains(reader.Value))
{
String cap = reader.Value;
reader.MoveToAttribute("name");
local_caps.Add(new KeyValuePair<String, String>(reader.Value, cap));
}
}
}
}
循环(寻找所有while
s)是否会一直读到文件的末尾,因此超出了它的假定范围(在{ {1}})?如果是这样,我该如何避免呢?非常感谢!
答案 0 :(得分:2)
这是XPath的理想工作:
doc.Load("file.xml");
var nodes = doc.SelectNodes("/datasources/datasource[@name='DS1']/column[@caption='C1']");
当然,要获得地图,您必须稍微改进一下这个示例:
string expectedDatasource = "DS1";
string expectedCaption = "C1";
string xpath = string.Format("/datasources/datasource[@name='{0}']/column[@caption='{1}']",
expectedDatasource, expectedCaption)
var local_caps = doc.SelectNodes(xpath)
.Cast<XmlElement>()
.ToDictionary(x => x.GetAttribute("name"),
x => x.GetAttribute("caption"));