2

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.

4 Answers 4

4

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();
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

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.

Comments

0

Try using XPATH

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.