1

I am generating an XML file from linq query. The xml elements are generated, however I want to add a prefix in each element so it result some thing like the following:-

XDocument xDoc =null;

xDoc = new XDocument(
                    new XDeclaration("1.0", "utf-8", "yes"),
                    new XElement("EmpLists",
                        new XElement("Employee",
                            new XElement("EmpId", '1'),
                            new XElement("Name", "Sam"),
                            new XElement("Sex", "Male"))));

What should I do to have the elements print with their prefix "CP:" as shown below?

<?xml version="1.0" encoding="utf-8" ?>
<CP:EmpLists>
 <CP:Employee>
    <CP:EmpId>1</CP:EmpId>
    <CP:Name>Sam</CP:Name>   
    <CP:Sex>Male</CP:Sex>
   <CP:Address>
      <CP:Street>7A Cox Street</CP:Street>
      <CP:City>Acampo</CP:City>
      <CP:State>CA</CP:State>
      <CP:Zip>95220</CP:Zip>
    </CP:Address>
 </CP:Employee>
 <CP:Employee>
    <CP:EmpId>2</CP:EmpId>
    <CP:Name>Lucy</CP:Name>
    <CP:Sex>Female</CP:Sex>
    <CP:Address>
      <CP:Street>Jess Bay</CP:Street>
      <CP:City>Alta</CP:City>
      <CP:State>CA</CP:State>
      <CP:Zip>95701</CP:Zip>
    </CP:Address>
 </CP:Employee>
 </CP:EmpLists>
Sam Axe
  • 33,313
  • 9
  • 55
  • 89
Xmare2
  • 19
  • 1
  • 1
  • 6
  • https://msdn.microsoft.com/en-us/library/bb387069.aspx (I'm not a dotnetter, so I'll leave to someone else to construct the actual answer if this doesn't help) – Amadan Mar 25 '15 at 01:07

2 Answers2

4

This works for me:

var url = "YOUR_NS_URL";
var ns = XNamespace.Get(url);

var xDoc =
    new XDocument( 
        new XDeclaration("1.0", "utf-8", "yes"),
        new XElement(ns + "EmpLists",
            new XAttribute(XNamespace.Xmlns + "CP", url),
            new XElement(ns + "Employee",
                new XElement(ns + "EmpId", '1'),
                new XElement(ns + "Name", "Sam"),
                new XElement(ns + "Sex", "Male"))));

I get this XML:

<CP:EmpLists xmlns:CP="YOUR_NS_URL">
  <CP:Employee>
    <CP:EmpId>1</CP:EmpId>
    <CP:Name>Sam</CP:Name>
    <CP:Sex>Male</CP:Sex>
  </CP:Employee>
</CP:EmpLists>
Enigmativity
  • 113,464
  • 11
  • 89
  • 172
0

You will want to utilize a namespace, see the similar namespace example. You will need to instantiate an instance, of XNamespace, and use it as an XAttribute, using new XAttribute(XNamespace.Xmlns + "CP", ns).

Community
  • 1
  • 1
Quinn Johns
  • 376
  • 4
  • 16
  • your example was very helpful and actually the same solution as 'Enigmativity'. Thanks you! – Xmare2 Mar 25 '15 at 19:09