简体   繁体   English

如何使用C#在XML中使用元素属性值获取子节点

[英]How to get child nodes using element attribute value in XML using C#

i am trying to get all the child nodes using attribute class. 我正在尝试使用属性类获取所有子节点。 My code is 我的代码是

string xmlText = File.ReadAllText(@"G:\\car_words_xml.xml");
var doc = new XmlDocument();
doc.LoadXml(xmlText);
var result = doc.SelectNodes("//*[@class='سوزوکی']");           
foreach (XmlNode node in result)
{
foreach (XmlNode childNode in node.ChildNodes)
{
textBox1.Text= textBox1.Text+ Environment.NewLine+childNode.InnerText;
}
} 

in this code i have given value for class attribute. 在这段代码中,我给了class属性值。 what if i want to use a variable say x instead of value so tht output of this code depends on tht varaible value. 如果我想使用变量说x而不是值怎么办,那么此代码的输出取决于可变值。

You can use a string variable and concatenate the variable with the XPath expression like below 您可以使用字符串变量,并将变量与XPath表达式连接起来,如下所示

string x = ...; // set the value here
var result = doc.SelectNodes("//*[@class='" + x + "']");           
foreach (XmlNode node in result)
{
    foreach (XmlNode childNode in node.ChildNodes)
    {
        textBox1.Text= textBox1.Text+ Environment.NewLine+childNode.InnerText;
    }
} 

Alternatively, you can use String.Format() to stuff dynamic substring value into the XPath string. 另外,您可以使用String.Format()将动态子字符串值填充到XPath字符串中。 This, IMHO, is better to avoid problems such as missing single quotes (single quote directly before/after double quote is rather hard to read and you may not notice when it is missing) : 恕我直言,这更好地避免了诸如单引号丢失的问题(双引号之前/之后的单引号很难阅读,并且丢失时您可能不会注意到):

var x = "سوزوکی";
var xpath = String.Format("//*[@class='{0}']", x);
var result = doc.SelectNodes(xpath);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM