0

I'm trying to test the Linq for retrieving some values of elements in the xml file:

Here is the code:

  try
        {
            XElement doc = XElement.Load(@"Z:\test.xml");

            string abc, def;


            foreach (XElement elm in doc.Descendants().Elements("test"))
            {
                abc = elm.Element("att").Value;
                def = elm.Element("title").Value;
                Console.WriteLine(abc);
                Console.WriteLine(def);
            }
        }

        catch (XmlException xe)
        {
            Console.WriteLine(xe);
        }

But this doesn't seem to go through the foreach loop. It's not giving me any error. I have debugged it and it reads the xml file just fine. But when it reaches the foreach loop, it just quits. What's the reason.

Part of my XML FILE:

<root xmlns:xsi="w3.org/2001/XMLSchema-instance"; xsi:noNamespaceSchemaLocation="test.xsd">
<test att="123" title="XXXX" />
<test att="2324" title="YYYY" />
</root>
5
  • it's not a valid xml and it should throw an exception. Xml is required to have a single root node May 22, 2013 at 12:56
  • that is not a valid xml file May 22, 2013 at 12:57
  • THe xml file is valid, it's just that I have written a part of it to show you what it looks like. It's being picked up properly when I debug.
    – user726720
    May 22, 2013 at 12:59
  • @user726720 could you give the exact xml, that you have? May 22, 2013 at 13:04
  • @user726720 with your edit, the problem could be trivial... I would not expect those to be found; they are not child-elements of descendants of the root... May 22, 2013 at 13:09

2 Answers 2

2

First we must note that

foreach (XElement elm in doc.Descendants().Elements("test"))

will only find elements that are not the root, not the immediate children of the root, but are at least 2 levels down; that is necessary to be a child-element of a descendant of the root. So: are your elements at least 2 levels down? If not:


Since you say it loads, this is probably a namespace issue. I'm guessing you have something like:

<foo xmlns="blahblahblah">
    ...
    <test>...</test>
</foo>

or

<bar:foo xmlns:bar="blahblahblah">
    ...
    <test>...</test>
</bar:foo>

in which case the name of those elements is not test, it is blahblahblah:test. To query that, you need to use a full XName.

For a concrete example:

string text = @"<foo xmlns=""blah""><test/></foo>";
var doc = XDocument.Parse(text);
var el0 = doc.Root.Element("test"); // null
XNamespace ns = "blah";
var el1 = doc.Root.Element(ns + "test"); // not null

Obviously you need to use the right namespace in your code, then .Elements(ns + "test").

5
  • Here is the namespace: xmlns:xsi="w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="test.xsd">, is the right header
    – user726720
    May 22, 2013 at 13:40
  • does your answer apply to this namespace as stated
    – user726720
    May 22, 2013 at 13:43
  • I have edited my question to add the namespaces to the XML file, the elements are without the ns as you mention in your solution above. Can you please check if this would work. Thanks
    – user726720
    May 22, 2013 at 14:56
  • @user726720 if the xml shown is you actual xml, then the problem is what I said at the top: the elements you show are not child-elements of descendants of the root element. So it is entirely correct that they do not get returned by your query. May 22, 2013 at 22:06
  • @MarcGravell, I was missing the namespace. Thank you, this saved me time! Aug 9 at 5:39
1

First of all you need to have single root element otherwise it will throw exception:

<testRoot>
    <test att="123" title="XXXX" />
    <test att="2324" title="YYYY" />
</testRoot>

And code should be as below:

//Not XElement but XDocument
XDocument doc = XDocument.Load(@"D:\test\test.xml");

string abc, def;

foreach (XElement elm in doc.Descendants().Elements("test"))
{
    //Not elm.Element but elm.Attribute
    abc = elm.Attribute("att").Value;
    def = elm.Attribute("title").Value;
    Console.WriteLine(abc);
    Console.WriteLine(def);
}
4
  • Thanks that works. But why not xelement instead of xdocument when loading the file.
    – user726720
    May 22, 2013 at 13:10
  • I don't really know. But you are loading whole xml document. you can still load document as XElement.Load() but then you have to use doc.Elements("test") instead of doc.Descendants().Elements("test"). I think Mark Gravel explained the reason May 22, 2013 at 13:14
  • The biggest difference between XElement and XDocument, IIRC, is that when using XDocument, you'll get a <?xml version='1.0' encoding='utf-8'?> processing instruction, whereas loading into a XElement will result in a "document fragment" and not a full-fledged XML document (i.e. an XML document that includes the xml processing instruction). May 22, 2013 at 15:56
  • Also, I think @Adil Mammadav is correct here; the main problem with your original code was that you were looking for elements att and title, but in your XML example, they were attributes. But if you do have namespaces in your XML, then @Mark Gravell has nicely stated what you need to do in that situation. May 22, 2013 at 15:58

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.