我有以下嵌套循环
foreach (XmlNode nodeT in root.ChildNodes)
{
foreach (XmlNode nodeServicio in nodeT.ChildNodes)
{
nombreMayusculas = nodeServicio.Name.ToUpper();
if (nombreMayusculas.Contains("SERVICE"))
{
int a = 0;
int.TryParse(nombreMayusculas.Replace("SERVICE", ""), out a);
if (a.Equals(Type))
{
//some logic here to process only the matching Xmlnode
}
}
}
}
修改 有没有办法只循环匹配两个条件的匹配XmlNodes?
我尝试使用Where
linq方法,但不可用,我已经拥有using System.Linq
这是XML
<Clients>
<AgoraCOR1 Type=\"SP\" Default=\"False\">
<Connectionstring>CONN_STRING</Connectionstring>
<Service002>SaveOperationNotification</Service002>
<Service106>SaveOrderNotification</Service106>
</AgoraCOR1>
<SerficorpOrdenes1 Type=\"SP\" Default=\"False\">
<Connectionstring>CONN_STRING</Connectionstring>
<Service106>SaveOrderNotification</Service106>
<Service017>SaveComplementationNotification</Service017>
</SerficorpOrdenes1>
<CorrevalCORInterno1 Type=\"SP\" Default=\"False\">
<Connectionstring>CONN_STRING</Connectionstring>
<Service002>SaveOperationNotification</Service002>
<Service074>SaveIndicatorNotification</Service074>
<Service106>SaveOrderNotification</Service106>
<Service017>SaveComplementationNotification</Service017>
<Service072>SalvarNotificacionPreciosDeMercado</Service072>
</CorrevalCORInterno1>
</Clients>
答案 0 :(得分:1)
目前还不完全清楚你的xml是怎样的,但我想你的服务节点的名称如 service1 , service2 等。你可以使用正则表达式来测试如果节点名称与服务类型匹配(如果xml结构不同,则可以更改模式):
var xdoc = XDocument.Load(path_to_xml);
Regex regex = new Regex(String.Format("^Service{0}$", Type));
var services = from s in xdoc.Root.Elements().Elements()
where regex.IsMatch(s.Name.LocalName)
select s;
使用XPath的替代解决方案(您应该添加System.Xml.XPath)命名空间:
var xpath = String.Format("Clients/*/*[name() = 'Service{0}']", Type);
var services = xdoc.XPathSelectElements(xpath);
与旧的XmlDocument类相同的解决方案:
XmlDocument doc = new XmlDocument();
doc.Load(path_to_xml);
foreach(XmlNode nodeServicio in doc.SelectNodes(xpath)) // xpath same as above
// use nodeServicio
答案 1 :(得分:0)
您可以使用Linq - 但它将具有与您已经完成的相同的性能配置文件:
var nodesToProcess = root
.ChildNodes
.ChildNodes
.Where(n => n.Name.ToUpper().Contains("SERVICE")));
foreach(var node in nodesToProcess)
{
....
}
答案 2 :(得分:0)
第二个循环可以重写如下。
var result = from nodeServicio in nodeT.ChildNodes
where nodeServicio.Name.ToUpper().Contains("SERVICE")
select nodeServicio;//or something else
编辑:
从你发布的代码中......我猜测子节点的值会看起来像SERVICE123,12SERVICE等
int type = 5; //integer
if (nombreMayusculas.Contains("SERVICE"))
{
int a = 0;
int.TryParse(nombreMayusculas.Replace("SERVICE", ""), out a);
//You cannot use Equals here.. used only for string comparison
if (a == type))
{
//some logic here to process only the matching Xmlnode
}
}