问题描述
我需要获取一个SubTopic元素的值,该元素具有一个名为名称"的属性
,具有特定值.我是这样做的;
I need to get a value of a SubTopic element which has an attribute
called "Name" with specific value. I do it this way;
IEnumerable<XElement> list =
(from el in xdoc.Elements()
where (string)el.Attribute("Name") == "creatingTests"
select el);
该集合具有零个元素.
我尝试放置 xdoc.Elements("SubTopic")
而不是空参数,但是没有成功.
I tried putting xdoc.Elements("SubTopic")
instead of empty parameter, but with no success.
我的XML文件结构;
My XML file structure;
<?xml version="1.0" encoding="windows-1250" ?>
<Help Title="TestTool - tematy pomocy">
<Topic Name="creatingTests" Title="Tworzenie testów">
<SubTopic Name="saveload" Title="Zapis i odczyt z pliku">
Content
</SubTopic>
</Topic>
</Help>
如何获得Help/Topic(Name ="creatingTests")的值?
How can I get that value of Help/Topic(Name="creatingTests")?
xdoc
当然是带有已加载xml的 XDocument
对象,它确实具有我文件的内容.
xdoc
is of course XDocument
object with loaded xml and it does have the content of my file.
推荐答案
xdoc.Elements()
仅返回一个元素-XML树的根(它是< Help>
元素在您的示例中.
xdoc.Elements()
returns only one element - the Root of XML tree (it's <Help>
element in your example.
将查询更改为:
IEnumerable<XElement> list =
(from el in xdoc.Root.Elements()
where (string)el.Attribute("Name") == "creatingTests"
select el);
它返回一个元素的集合.使用 First
或 FirstOrDefault
将其作为单个项目而不是集合获取:
It returns collection with one element. Use First
or FirstOrDefault
to get it as single item, not a collection:
XElement item = (from el in xdoc.Root.Elements()
where (string)el.Attribute("Name") == "creatingTests"
select el).FirstOrDefault();
这篇关于在C#中获取具有特定属性值的xml元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!