用C#读取XML指定节点下的值
2014-04-29 13:33
302 查看
<Employees>
<Employee name="李宇秋" age="23">
<Address>
长江路178号
</Address>
<Department>
演唱部
</Department>
</Employee>
<Employee name="曾不可" age="24">
<Address>
火星路239号
</Address>
<Department>
舞蹈部
</Department>
</Employee>
<Employee name="张学敌" age="27">
<Address>
香港街13号
</Address>
<Department>
偶像部
</Department>
</Employee>
</Employees>
要获取 name="曾不可" 的节点下面的 Address 节点的值“火星路239号”,C#如何实现?
OK,在linq之前,可以试用XMLDocment将xml整个文件读进来,然后比如可以用xpath再进行分析。
自从有了linq,一切都变得简单了,实现代码如下:
view sourceprint?
//假设以上xml我们保存在一个本地xml文件 D:\Microsoft Work\XMLPath\sampleXML.xml 中
public List<string> GetXMLResult()
{
XElement xelement = XElement.Parse(@"D:\Microsoft Work\XMLPath\sampleXML.xml");
var query = xelement.Descendants("Employee").Where(x => x.Attribute("name").Value == "曾不可").Select(x => x.Element("Address").Value);
if (query != null && query.Count() > 0)
return query.ToList<string>();
return null;
}
<Employee name="李宇秋" age="23">
<Address>
长江路178号
</Address>
<Department>
演唱部
</Department>
</Employee>
<Employee name="曾不可" age="24">
<Address>
火星路239号
</Address>
<Department>
舞蹈部
</Department>
</Employee>
<Employee name="张学敌" age="27">
<Address>
香港街13号
</Address>
<Department>
偶像部
</Department>
</Employee>
</Employees>
要获取 name="曾不可" 的节点下面的 Address 节点的值“火星路239号”,C#如何实现?
OK,在linq之前,可以试用XMLDocment将xml整个文件读进来,然后比如可以用xpath再进行分析。
自从有了linq,一切都变得简单了,实现代码如下:
view sourceprint?
//假设以上xml我们保存在一个本地xml文件 D:\Microsoft Work\XMLPath\sampleXML.xml 中
public List<string> GetXMLResult()
{
XElement xelement = XElement.Parse(@"D:\Microsoft Work\XMLPath\sampleXML.xml");
var query = xelement.Descendants("Employee").Where(x => x.Attribute("name").Value == "曾不可").Select(x => x.Element("Address").Value);
if (query != null && query.Count() > 0)
return query.ToList<string>();
return null;
}
相关文章推荐
- 用C#读取XML指定节点下的值
- c#用XmlDocument读取指定节点
- C#读取XML节点
- C#读取xml文件指定节点下的值
- 转] C#下 读取xml节点的数据总结
- C#读取xml节点数据方法小结
- C#读取xml节点数据方法小结
- C#解析xml(获取指定节点值)
- 使用C#读取XML节点,修改XML节点
- C#中读取xml文件指定节点
- c# 读取xml节点
- C#读取XML每个节点
- C#中读取xml文件指定节点
- C# xml 读取 编辑保存 新增保存 查找是否存在特定节点
- C#通过XML节点属性/属性值读取写入XML操作代码实例
- C#下 读取xml节点的数据总结
- C# 读取xml中特定节点的属性值 xmldocument方式
- C#中读取xml文件指定节点
- xml 读取节点中指定的属性值
- C#-XML文件提取字符串+字符串存为XML文件+创建XML(自定义节点)文件+读取节点内容