C# - 访问XML属性

时间:2013-07-17 14:20:06

标签: c# xml

我想访问属性type,其中abc的值为female

XElement xelement = XElement.Load("..\\..\\Employees.xml");
var name = from nm in xelement.Elements("Employee")
            where (string)nm.(Element("Abc") == "Female").Attribute("Type") == "Att"
            select nm;

这不起作用。有什么方法可以实现吗?

3 个答案:

答案 0 :(得分:1)

这样的事情会起作用。看看Xml会很有用。

var doc = XDocument.Load("c:\\temp\\test.xml");
var result = doc.Descendants("Employee")
                .Where(x=>(string)x.Value== "female")
                .Select(x=>x.Attribute("type").Value);

这假设xml是这样的,查询将返回“foo1”。

<?xml version="1.0"?>
<root>-
   <Employee type="foo">
      <abc>male</abc>
   </Employee>
   <Employee type="foo1">
      <abc>female</abc>
   </Employee>
   <Employee type="foo2">
      <abc>male</abc>
   </Employee>
</root>

答案 1 :(得分:0)

您的代码没有任何意义。

你无法嵌套比较,强制转换和类似对象。

相反,您需要使用&&运算符分别检查每个条件。

答案 2 :(得分:0)

使用XMLReader

来自MSDN的更多信息:http://msdn.microsoft.com/en-us/library/system.xml.xmlreader.aspx