2

I don't want to include xmlns + "ElementName" for every element name?

XDocument xml = XDocument.Load(@"C:\file.xml");
XNamespace xmlns = "http://www.com/namespace";
var vehicles = from vehicle in xml.Descendants(xmlns + "Element")
               select vehicle.Element(xmlns + "Item")
};
Nick Strupat
  • 4,928
  • 4
  • 44
  • 56
  • Can `xmlns` be converted to a `string` and could this be done `xml = xml.Replace(xmlns.ToString(), "")`? – Bastardo Aug 08 '11 at 18:36

3 Answers3

4

Unfortunately this is what you must do when working with LINQ to XML. You must provide the namespace each time you query the document for a particular element.

Andrew Hare
  • 344,730
  • 71
  • 640
  • 635
0

Even it is too late but maybe it helps someone else like me!

You can add an extention method to act as a wrapper for the built in one!

Like so:

public static class XDoncumentExtentions
{
    private static string DefaultNamespace = "{http://schemas.openxmlformats.org/spreadsheetml/2006/main}";
    public static IEnumerable<XElement> DescendantsSimple(this XContainer me, string simpleName)
    {
        return me.Descendants(string.Format("{0}{1}", DefaultNamespace, simpleName));
    }

    public static IEnumerable<XElement> ElementsSimple(this XContainer me, string simpleName)
    {
        return me.Elements(string.Format("{0}{1}", DefaultNamespace, simpleName));
    }

    public static XElement ElementSimple(this XContainer me, string simpleName)
    {
        return me.Element(string.Format("{0}{1}", DefaultNamespace, simpleName));
    }
}
A77
  • 172
  • 1
  • 7
0

Looks like Scott Hanselman has written some notes on it a while ago. Not exactly what you are lookin for, maybe (there are some Linq to XML examples a bit down in the post), but here's the link, anyhow: http://www.hanselman.com/blog/GetNamespacesFromAnXMLDocumentWithXPathDocumentAndLINQToXML.aspx

See also this SO question: How to set the default XML namespace for an XDocument

Community
  • 1
  • 1
Erik A. Brandstadmoen
  • 10,430
  • 2
  • 37
  • 55