xml序列化 - 删除命名空间

时间:2011-11-09 06:17:35

标签: c# xml-serialization

我使用c#序列化对象。我正在以下面的格式得到结果

  <?xml version="1.0"?>
    <Users xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
      <Users>
        <User Id="11005477969327" CreateDate="06/03/2011" LastSendDate="1/1/0001" />
        <User Id="11034688201594" CreateDate="04/22/2012" LastSendDate="1/1/0001" />
       <Users 
    </User>

但我想要这种格式的结果。

<?xml version="1.0"?>
<Users>
  <User Id="11005477969327" SendDate="1/1/0001" NextSendDate="2/7/2012 11:13:30 AM" />
  <User Id="11034688201594" SendDate="1/1/0001" NextSendDate="2/7/2012 11:13:30 AM" />

</Users>

这里是我的代码

public class Users
    {
        [XmlArray("Users")]
        public List<User> ListData { get; set; }

        public string GetXML()
        {
            System.IO.MemoryStream ms = new System.IO.MemoryStream();

            XmlSerializer sr = new XmlSerializer(typeof(Users));
            sr.Serialize(ms, this);

            ms.Position = 0;
            return System.Text.Encoding.UTF8.GetString(ms.ToArray());
        }
    }

    public class User
    {
        [XmlAttribute("Id")]
        public Int64 UserId { get; set; }

        [XmlAttribute("CreateDate")]
        public string CreateDate { get; set; }

        [XmlAttribute("LastSendDate")]
        public string LastSendDate { get; set; }


    }

3 个答案:

答案 0 :(得分:56)

您只需将[XmlArray("Users")]替换为[XmlElement("User")]

即可

此属性告诉序列化程序,您要将所有这些用户项目存储在特定节点&#34;用户&#34;下,如果您将其替换为XmlElement,则serialzer将所有这些用户内联存储(右下方)第一个用户标签)就像你喜欢它一样。

至于xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"名称空间。它们是自动添加的,但它们是无害的,因为所有元素都在默认命名空间中。您可以在XmlSerializer来电中添加以下代码,以便删除这些代码:

var xns = new XmlSerializerNamespaces();
var serializer = new XmlSerializer(users.GetType());
xns.Add(string.Empty, string.Empty);
//...
serializer.Serialize(stream, users, xns);

答案 1 :(得分:2)

你应该写:

XmlSerializer sr = new XmlSerializer(typeof(Users));
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("","");
sr.Serialize(ms, this, ns);

答案 2 :(得分:-6)

快速解决方案 - 转换为字符串,然后删除 - 使用按钮单击开始执行。

Imports System.IO
Public Class Form1
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
    Dim mydoc As XElement = XElement.Load("C:\Users\Documents\myfile.XML")
    Dim y As String = mydoc.ToString
    Dim z As String = mydoc.Name.Namespace.ToString
    Dim getrid As String = " xmlns=" & Chr(34) & z & Chr(34)
    y = Replace(y, getrid, "")
    Dim tr As TextReader = New StringReader(y)
    Dim newdoc As XElement = XElement.Load(tr)
    tr.Close()
    Debug.Print(newdoc.ToString)
End Sub
End Class