用于搜索属性的 XPath 变量 [英] XPath variable for searching attribute

查看:19
本文介绍了用于搜索属性的 XPath 变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个 c# 代码,它需要我解析一个 xml 文件.我需要的声明是

I am writing a c# code which requires me to parse an xml file. The statement that i need is

  XmlDocument xmlt = new XmlDocument();
  xmlt.Load(XMLFile1.xml");
  XmlNode node = xmlt.SelectSingleNode("//abc/data[@name='xyz']/value");

其中 abc 是根节点.我正在搜索数据属性@name 以与 xyz 匹配,如果我需要一个变量而不是硬编码 xyz,我应该怎么做,比如 name_var.我基本上需要一个执行该功能的代码,以便我可以将@name=name_var 而不是 xyz.

where abc is the root node. I am searching the data attribute @name to match with xyz, what should i do if instead of hard coding xyz i need a variable, say name_var. I basically need a code which performs the function so that i cn put @name=name_var instead of xyz.

name_var 在 c# 代码中不同

name_var is varied in the c# code

推荐答案

据我所知 SelectNodesSelectSingleNode 方法没有提供重载来提供一些变量分辨率,所以你所能做的就是构造一个字符串,例如

As far as I know the SelectNodes and SelectSingleNode methods do not provide an overload to provide some variable resolution so all you can do is construct a string e.g.

string name = "xyx";
XmlNode node = xmlt.SelectSingleNode(string.Format("abc/data[@name = '{0}']/value", name));

当然,只要 name 值包含单引号 ' 字符,这种方法就会中断.如果您需要 XPath 中的可变分辨率,请查看 XPathNavigator,它可以通过一些努力来实现:http://msdn.microsoft.com/en-us/library/vstudio/dd567715%28v=vs.100%29.aspx.

Of course that approach breaks as soon as the name value contains a single quote ' character. If you need variable resolution in XPath then look into XPathNavigator, it allows that with some effort: http://msdn.microsoft.com/en-us/library/vstudio/dd567715%28v=vs.100%29.aspx.

这篇关于用于搜索属性的 XPath 变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆