我有以下XML类型文件
<root>
<info version_id=... product_id=... account_id=...>
<CRM>
<result key=... value=...>
<result key=... value=...>
....
</CRM>
<result key=... value=....>
</info>
<info version_id=... product_id=... account_id=...>
<CRM>
<result key=... value=...>
<result key=... value=...>
....
</CRM>
<result key=... value=....>
</info>
</root>
我需要为每个"info"节点创建以下列表:列表(帐户+产品、键、值)而且我必须只获取作为CRM节点一部分的"键"one_answers"值"信息。
所以我想用这个代码
string[] directoryXml = Directory.GetFiles(directory);
var listxmlresult = new List<XmlResultNode>();
foreach (var xmlfile in directoryXml)
{
var docxml = new XmlDocument();
docxml.Load(xmlfile);
XmlNodeList nodesInfo = docxml.SelectNodes("//info");
XmlNodeList nodesResult = docxml.SelectNodes("//info/CRM/result");
foreach (XmlNode info in nodesInfo)
{
string VersionId = info.Attributes["version_id"].Value;
string ProductId = info.Attributes["product_id"].Value;
string AccountId = info.Attributes["account_id"].Value;
string AccountProductId = AccountId + " : " + ProductId;
// verify that CRM node exist
if (docxml.SelectSingleNode("//info/CRM") == null)
{
//To do log info that CRM node is not available for the specific file
}
foreach (XmlNode result in nodesResult)
{
//To do verfiy value is empty
string Key = result.Attributes["key"].Value;
string Value = result.Attributes["value"].Value;
if (Value.Length != 0)
{
var listXmlResultTemp = new XmlResultNode(AccountProductId, Key, Value);
listxmlresult.Add(listXmlResultTemp);
}
}
}
}
但是这段代码返回的列表包含每个"accountproduct"的所有"key" "value"。
我无法在第二个循环中只读取当前节点。我尝试了几种xpath可能性,但我无法使用XmlNodeList获取当前位置。
谢谢
这不是很清楚你试图达到张贴。我认为你应该这样修改内循环:
foreach (XmlNode result in info.SelectNodes("./CRM/result"))
{
string Key = result.Attributes["key"].Value;
string Value = result.Attributes["value"].Value;
.....
.....
}