Select XML Nodes by Name [C#]
2013-10-22 21:22
344 查看
原文 http://www.csharp-examples.net/xml-nodes-by-name/
To find nodes in an XML file you can use XPath expressions. Method XmlNode.SelectNodes returns a list of nodes selected by the XPath string. Method XmlNode.SelectSingleNode finds the first node that matches the XPath string.
Suppose we have this XML file.
[XML]
To get all <Name> nodes use XPath expression
[C#]
The output is:
To find nodes in an XML file you can use XPath expressions. Method XmlNode.SelectNodes returns a list of nodes selected by the XPath string. Method XmlNode.SelectSingleNode finds the first node that matches the XPath string.
Suppose we have this XML file.
[XML]
<Names> <Name> <FirstName>John</FirstName> <LastName>Smith</LastName> </Name> <Name> <FirstName>James</FirstName> <LastName>White</LastName> </Name> </Names>
To get all <Name> nodes use XPath expression
/Names/Name. The first slash means that the <Names> node must be a root node. SelectNodes method returns collection XmlNodeList which will contain the <Name> nodes. To get value of sub node <FirstName> you can simply index XmlNode with the node name:
xmlNode["FirstName"].InnerText. See the example below.
[C#]
XmlDocument xml = new XmlDocument(); xml.LoadXml(myXmlString); // suppose that myXmlString contains "<Names>...</Names>" XmlNodeList xnList = xml.SelectNodes("/Names/Name"); foreach (XmlNode xn in xnList) { string firstName = xn["FirstName"].InnerText; string lastName = xn["LastName"].InnerText; Console.WriteLine("Name: {0} {1}", firstName, lastName); }
The output is:
Name: John Smith Name: James White
相关文章推荐
- Select XML Nodes by Attribute Value [C#]
- C#操作xml SelectNodes,SelectSingleNode总是返回NULL原因和解决方案
- C#操作xml SelectNodes,SelectSingleNode总是返回NULL原因和解决方案
- C#操作xml SelectNodes,SelectSingleNode总是返回NULL原因和解决方案
- C#操作xml SelectNodes,SelectSingleNode xmlns 总是返回NULL 与 xPath 介绍
- C#操作xml SelectNodes,SelectSingleNode总是返回NULL 与 xPath 介绍
- c# xml XPath SelectNodes, SelectSingleNode 无法获取
- 黄聪:C#操作xml SelectNodes,SelectSingleNode通过 xPath 定位class包含Contains的DIV
- C#操作xml SelectNodes,SelectSingleNode总是返回NULL原因和解决方案
- C#操作xml SelectNodes,SelectSingleNode总是返回NULL 与 xPath 介绍
- C#操作xml SelectNodes,SelectSingleNode总是返回NULL 与 xPath 介绍
- C#操作xml SelectNodes,SelectSingleNode总是返回NULL 与 xPath 介绍
- C# XML SelectNodes/SelectSingleNode
- PHP - XML - Filtering XML Nodes by Namespace
- C#操作XML文档(XmlDocument、XmlNode、XmlAttribute、SelectSingleNode、SelectNodes、XmlNodeList)
- Spring 3.0 学习-DI 依赖注入_创建Spring 配置-使用一个或多个XML 文件作为配置文件,使用自动注入(byName),在代码中使用注解代替自动注入,使用自动扫描代替xml中bea
- getElementByID getElementsByName getElementsByTagName的区别和总结 +js+Mxl+xmlhttp
- [JavaScript] 兼容IE、FireFox、Chrome等浏览器的xml处理函数(xml同步/异步加载、xsl转换、selectSingleNode、selectNodes)
- xmlDoc.SelectNodes用法(获取不到节点时注意事项)
- 使用XmlDocument.SelectNodes遍历xml元素遇到的一个XPathException