C#从XML属性获取值 [英] C# get values from xml attributes
本文介绍了C#从XML属性获取值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何使用C#来获得属性行动和文件名的价值观正确的方式
How to get attribute "action" and "filename" values in a right way using C#?
XML:
<?xml version="1.0" encoding="utf-8" ?>
<Config version="1.0.1.1" >
<Items>
<Item action="Create" filename="newtest.xml"/>
<Item action="Update" filename="oldtest.xml"/>
</Items>
</Config>
C#:我不能得到属性值,以及如何获取值在foreach循环? ?如何解决这个
C#: i cannot get attribute values as well as how to get values in foreach loops? How to solve this?
var doc = new XmlDocument();
doc.Load(@newFile);
var element = ((XmlElement)doc.GetElementsByTagName("Config/Items/Item")[0]); //null
var xmlActions = element.GetAttribute("action"); //cannot get values
var xmlFileNames= element.GetAttribute("filename"); //cannot get values
foreach (action in xmlActions)
{
//not working
}
foreach (file in xmlFileNames)
{
//not working
}
您的代码例如很多手段对我。谢谢!
Your code example means alot to me. Thanks!
推荐答案
您可以使用 LINQ到XML 。下面的查询返回强类型项目的集合,动作
和文件名
属性:
You can use LINQ to XML. Following query returns strongly typed collection of items with Action
and FileName
properties:
var xdoc = XDocument.Load(@newFile);
var items = from i in xdoc.Descendants("Item")
select new {
Action = (string)i.Attribute("action"),
FileName = (string)i.Attribute("fileName")
};
foreach (var item in items)
{
// use item.Action or item.FileName
}
这篇关于C#从XML属性获取值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文