C#Object序列化到XML名称空间和仅在子元素中的前缀

时间:2017-07-31 13:17:26

标签: c# xml

如何在使用C#将对象序列化为XML时,在子级元素上设置名称空间?

XML我希望最终将其作为XML输出:

<clsPerson>
  <FirstName>Jeff</FirstName>
  <MI>J</MI>
  <LastName>Jefferson</LastName>
  <ns1:Addresses xmlns="www.whatever.co.uk">
    <Home>Here</Home>
    <Work>There</Work>
  </Addresses>
</clsPerson>

我使用的代码主要来自其他问题,如下所示:

using System;
using System.IO;
using System.Xml;
using System.Xml.Serialization;

public class clsPerson
{
   public string FirstName;
   public string MI;
   public string LastName;

   [XmlElement(Namespace = "www.whatever.co.uk")]
   public clsPlaces Addresses; 

       public clsPerson()
       {
         clsPlaces clsPlaces = new clsPlaces();
       }
 }

[XmlRoot(Namespace = "")]
public class clsPlaces
{
public string Home { get; set; }
public string Work { get; set; }
   }

class class1
{
 static void Main(string[] args)
{
    clsPerson p = new clsPerson();
    var xml = "";
    p.FirstName = "Jeff";
    p.MI = "J";
    p.LastName = "Jefefrson";
    p.Addresses = new clsPlaces();
    p.Addresses.Home = "Here";
    p.Addresses.Work = "There";

    var emptyNamepsaces = new XmlSerializerNamespaces(new[] {       XmlQualifiedName.Empty });
    var serializer = new XmlSerializer(p.GetType());
    var settings = new XmlWriterSettings();
    settings.Indent = true;
    settings.OmitXmlDeclaration = true;

   emptyNamepsaces.Add("ns", "www.whatever.co.uk");

    using (var stream = new StringWriter())
    using (var writer = XmlWriter.Create(stream, settings))
    {
        serializer.Serialize(writer, p, emptyNamepsaces);
        xml =  stream.ToString();
    }

       Console.WriteLine(xml)
       Console.ReadLine();
    }
}

以上给出:

<clsPerson xmlns:ns="www.whatever.co.uk">
  <FirstName>Jeff</FirstName>
  <MI>J</MI>
  <LastName>Jefefrson</LastName>
  <ns:Addresses>
    <Home>Here</Home>
    <Work>There</Work>
  </ns:Addresses>

我如何仅在元素上获取xmlns?我已经尝试了所有我可以看到的搜索stackoverflow,但无法找到/理解答案。

由于

1 个答案:

答案 0 :(得分:0)

删除它 - 添加命名空间将确保将前缀添加到根目录:

emptyNamepsaces.Add("ns", "www.whatever.co.uk");

地址声明将自动添加。您还需要从clsPlaces中删除空名称空间,否则HomeWork的namspace将不正确:

public class clsPlaces
{
    public string Home { get; set; }
    public string Work { get; set; }
}

输出将如下所示:

<clsPerson>
  <FirstName>Jeff</FirstName>
  <MI>J</MI>
  <LastName>Jefefrson</LastName>
  <Addresses xmlns="www.whatever.co.uk">
    <Home>Here</Home>
    <Work>There</Work>
  </Addresses>
</clsPerson>

请参阅this fiddle了解演示。