Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XElement namespaces (How to?)

How to create xml document with node prefix like:

<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 getting exception

Unhandled Exception: System.Xml.XmlException: The ':' character, hexadecimal val ue 0x3A, cannot be included in a name.
at System.Xml.XmlConvert.VerifyNCName(String name, ExceptionType exceptionTyp e)
at System.Xml.Linq.XName..ctor(XNamespace ns, String localName)
at System.Xml.Linq.XNamespace.GetName(String localName)
at System.Xml.Linq.XName.Get(String expandedName)

like image 655
Edward83 Avatar asked Feb 13 '11 18:02

Edward83


People also ask

How do I change a namespace in XML?

You can control namespace prefixes when serializing an XML tree in C# and Visual Basic. To do this, insert attributes that declare namespaces.

What is an XElement?

The XElement class is one of the fundamental classes in LINQ to XML. It represents an XML element. The following list shows what you can use this class for: Create elements. Change the content of the element.

What is XName?

XName does not contain any public constructors. Instead, this class provides an implicit conversion from String that allows you to create an XName. The most common place you use this conversion is when constructing an element or attribute: The first argument to the XElement constructor is an XName.


2 Answers

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> 
like image 71
Jon Skeet Avatar answered Oct 13 '22 04:10

Jon Skeet


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 
like image 26
Adam Rackis Avatar answered Oct 13 '22 04:10

Adam Rackis