XElement namespaces (How to?) XElement namespaces (How to?) xml xml

XElement namespaces (How to?)


It's really easy in LINQ to XML:

XNamespace ns = "sphinx";XElement element = new XElement(ns + "docset");

Or to make the "alias" work properly to make it look like your examples, something like this:

XNamespace ns = "http://url/for/sphinx";XElement element = new XElement("container",    new XAttribute(XNamespace.Xmlns + "sphinx", ns),    new XElement(ns + "docset",        new XElement(ns + "schema"),            new XElement(ns + "field", new XAttribute("name", "subject")),            new XElement(ns + "field", new XAttribute("name", "content")),            new XElement(ns + "attr",                          new XAttribute("name", "published"),                         new XAttribute("type", "timestamp"))));

That produces:

<container xmlns:sphinx="http://url/for/sphinx">  <sphinx:docset>    <sphinx:schema />    <sphinx:field name="subject" />    <sphinx:field name="content" />    <sphinx:attr name="published" type="timestamp" />  </sphinx:docset></container>


You can read the namespace of your document and use it in queries like this:

XDocument xml = XDocument.Load(address);XNamespace ns = xml.Root.Name.Namespace;foreach (XElement el in xml.Descendants(ns + "whateverYourElementNameIs"))    //do stuff