如何在xml元素中添加冒号? Linq到xml C#

时间:2015-03-25 01:00:38

标签: c# xml linq

我正在从linq查询生成XML文件。生成了xml元素,但是我想在每个元素中添加一个前缀,因此它会产生如下内容: -

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"))));

如何使用前缀“CP:”打印元素,如下所示?

<?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>

2 个答案:

答案 0 :(得分:3)

这对我有用:

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"))));

我得到这个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>

答案 1 :(得分:0)

您需要使用命名空间,请参阅类似的命名空间example。您需要使用XNamespace实例化XAttribute的实例,并将其用作new XAttribute(XNamespace.Xmlns + "CP", ns)