XElement namespaces (how?)

How to create an XML document with a node prefix, for example:

<sphinx:docset> <sphinx:schema> <sphinx:field name="subject"/> <sphinx:field name="content"/> <sphinx:attr name="published" type="timestamp"/> </sphinx:schema> 

When I try to run something like new XElement("sphinx:docset") I get an exception

Unhandled exception: System.Xml.XmlException: character ':', hex val ue 0x3A, cannot be included in the name.
in System.Xml.XmlConvert.VerifyNCName (string name, ExceptionTypeTyp e exception)
in System.Xml.Linq.XName..ctor (XNamespace ns, String localName)
in System.Xml.Linq.XNamespace.GetName (String localName)
in System.Xml.Linq.XName.Get (String extendedName)

+66
c # xml namespaces linq
Feb 13 '11 at 18:24
source share
2 answers

In LINQ for XML, this is very simple:

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

Or, so that the "alias" works correctly so that it looks 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")))); 

It 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> 
+104
Feb 13 '11 at 18:31
source share

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

 XDocument xml = XDocument.Load(address); XNamespace ns = xml.Root.Name.Namespace; foreach (XElement el in xml.Descendants(ns + "whateverYourElementNameIs")) //do stuff 
+20
Feb 13 '11 at 18:35
source share



All Articles