开发者

Is there a way to set the default namespace to query from an XDocument?

开发者 https://www.devze.com 2023-03-27 01:35 出处:网络
I don\'t want to include xmlns + \"ElementName\" for every element name? XDocument xml = XDocument.Load(@\"C:\\file.xml\");

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开发者_C百科 xml.Descendants(xmlns + "Element")
               select vehicle.Element(xmlns + "Item")
};


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.


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


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

精彩评论

暂无评论...
验证码 换一张
取 消