Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I write xml with a namespace and prefix with XElement?

Tags:

This may be a beginner xml question, but how can I generate an xml document that looks like the following?

<root xmlns:ci="http://somewhere.com" xmlns:ca="http://somewhereelse.com">     <ci:field1>test</ci:field1>     <ca:field2>another test</ca:field2> </root> 

If I can get this to be written, I can get the rest of my problem to work.

Ideally, I'd like to use LINQ to XML (XElement, XNamespace, etc.) with c#, but if this can be accomplished easier/better with XmlDocuments and XmlElements, I'd go with that.

Thanks!!!

like image 434
Chris Conway Avatar asked Aug 27 '09 02:08

Chris Conway


People also ask

How do I add namespace prefix to XML element?

When using prefixes in XML, a namespace for the prefix must be defined. The namespace can be defined by an xmlns attribute in the start tag of an element. The namespace declaration has the following syntax. xmlns:prefix="URI".

What is namespace prefix in XML?

The namespace prefix is used as an alias for the complete namespace identifier. The parser sets XML-NAMESPACE-PREFIX before transferring control to the processing procedure when the operand of the XML PARSE statement is an alphanumeric data item and the RETURNING NATIONAL phrase is not specified.

What does XElement mean?

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.


2 Answers

Here is a small example that creates the output you want:

using System; using System.Xml.Linq;  class Program {     static void Main()     {         XNamespace ci = "http://somewhere.com";         XNamespace ca = "http://somewhereelse.com";          XElement element = new XElement("root",             new XAttribute(XNamespace.Xmlns + "ci", ci),             new XAttribute(XNamespace.Xmlns + "ca", ca),                 new XElement(ci + "field1", "test"),                 new XElement(ca + "field2", "another test"));     } } 
like image 104
Andrew Hare Avatar answered Sep 20 '22 03:09

Andrew Hare


Try this code:

string prefix = element.GetPrefixOfNamespace(element.Name.NamespaceName); string name = String.Format(prefix == null ? "{1}" : "{0}:{1}", prefix, element.Name.LocalName);` 
like image 26
Hariharan Avatar answered Sep 23 '22 03:09

Hariharan