Traversing complex XML document in C# with XLinq

So I want to access the child element in a structure that looks like this:

<asdf:foobar attr="value">

I forget what the asdf is called, but it is what's causing the problem. My normal method of traversing in XLinq doesn't work:

xElem child = xDoc.Element("foobar");

Sets child to null because it claims there is no element foobar, and

xElem child = xDoc.Element("asdf:foobar");

Doesn't work because the compiler whines about the semicolon.

All help is appreciated, and thanks in advance!


I've been working on a reproduction of this as an example (since I can't show you the actual code). My test code:

        Console.WriteLine("BEGIN TEST");

        const string MY_SCHEMA = "";

        XElement xTest =
        new XElement("{" + MY_SCHEMA + "}base",
            new XAttribute("{" + XML_STANDARD + "}boofar", MY_SCHEMA),
            new XAttribute("attr1", "val"),
            new XElement("{" + MY_SCHEMA + "}asdf", "ghjkl")

        result.Text = xTest.ToString();

        XElement xOps2 = xTest.Element(XName.Get("asdf", MY_SCHEMA));
        XElement xSubOps2;

        if (xOps2 == null)
            xSubOps2 = xOps2.Element(XName.Get("asdf", MY_SCHEMA));

        Console.WriteLine("END TEST");

        MessageBox.Show("END TEST");

This displays the XML that I want:

<boofar:base xmlns:boofar="" attr1="val">

And everything is working great. Thanks all!


Unfortunately the implicit conversion from string to XName does not parse out the namespace. You need to do this:

XName.Get("foobar", "asdf");

Another way you can handle namespaces is by using the XNamespace class.

  XNamespace ns = "";
  XElement child = new XElement(ns + "base");

Need Your Help

Manually upgraded a MVC web app from 3 to 4, can't add API Controllers

I upgraded my web app from MVC3 to 4 recently by creating a new web application in MVC4, and copying all the files over, and finally merging the web.config. All works well with the existing web app,

How to add .apk file inside intent

android android-intent android-sharing

I want to add .apk file inside intent. I want to create a button "Share" which will share the whole app through bluetooth or any other application which have capability to send application. If this...