Skip to main content
 首页 » 编程设计

c#之在 C# 中获取具有特定属性值的 xml 元素

2024年02月13日14over140

我需要获取一个 SubTopic 元素的值,该元素具有一个名为“Name”的 attribute,具有特定的值。我是这样做的;

 IEnumerable<XElement> list = 
        (from el in xdoc.Elements() 
         where (string)el.Attribute("Name") == "creatingTests" 
         select el); 

该集合有零个元素。

我尝试使用 xdoc.Elements("SubTopic") 代替空参数,但没有成功。

我的 XML 文件结构;

<?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") 的值?

xdoc 当然是加载了 xml 的 XDocument 对象,它确实有我文件的内容。

请您参考如下方法:

xdoc.Elements()仅返回一个元素 - XML 树的根(在您的示例中为 <Help> 元素。

将您的查询更改为:

IEnumerable<XElement> list = 
    (from el in xdoc.Root.Elements() 
     where (string)el.Attribute("Name") == "creatingTests" 
     select el); 

它返回包含一个元素的集合。使用 First或 FirstOrDefault将其作为单个项目而不是集合:

XElement item = (from el in xdoc.Root.Elements() 
                 where (string)el.Attribute("Name") == "creatingTests" 
                 select el).FirstOrDefault();