![](/img/trans.png)
[英]Nested XmlDocument/XML to DataTable or DataSet Conversion in C#
[英]C# XmlDocument: Nested objects
我有一個具有以下格式的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
-滿足特定條件的columns
name
映射(即,具有預期的caption
並且是預期的datasource
的column
)。
目前,我有此代碼,但我對此並不自信。
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
循環(查找所有column
s)是否會一直讀取到文件末尾,從而超出其假定的范圍(在其datasource
)? 如果是這樣,我應該如何避免呢? 非常感謝!
這是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"));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.