Get a xml element with specific attribute value in c#

情到浓时终转凉″ 提交于 2021-02-19 05:38:05

问题


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);

The collection has zero elements.

I tried putting xdoc.Elements("SubTopic") instead of empty parameter, but with no success.

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>

How can I get that value of Help/Topic(Name="creatingTests")?

xdoc is of course XDocument object with loaded xml and it does have the content of my file.


回答1:


xdoc.Elements() returns only one element - the Root of XML tree (it's <Help> element in your example.

Change your query to:

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

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();



回答2:


Here's an alternative by using System.Xml.XPath:

using System.Xml.Linq;
using System.Xml.XPath;

class Program
{
    static void Main(string[] args)
    {
        var xdoc = XDocument.Load("input.xml");
        var subTopic = xdoc
            .XPathSelectElement("//Topic[@Name='creatingTests']/SubTopic");
    }
}



回答3:


Very easy and simplest way is to use XSLT..

1.Create an XSLT Template.

2.Call it in c#.

xmlDaynamic.DocumentContent = "Your XML Input";
xmlDaynamic.TransformSource = "YourTemplate with extension";

3.Your task is done.

4.xmlDaynamic is a server control.




回答4:


Try using XPATH

http://support.microsoft.com/kb/308333

"//Topic[@Name='creatingTests']"


来源:https://stackoverflow.com/questions/18206537/get-a-xml-element-with-specific-attribute-value-in-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!