简体   繁体   中英

How to add a colon inside xml element? Linq to xml C#

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>

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>

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) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM