简体   繁体   中英

Get a xml element with specific attribute value in c#

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.

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

Try using XPATH

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

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM