我该如何清理我的xml代码

时间:2012-01-05 12:48:11

标签: c# xml-serialization

序列化后该类的一个对象:

[XmlType("Person")] // define Type

public class Person
{
    [XmlElement("PropertyType")]
    public PropertyType PropertyType { get; set; }

    [XmlElement("ID")]
    public string ID { get; set; }

    [XmlElement("Name")]
    public string Name { get; set; }

    [XmlElement("City")]
    public string City { get; set; }

    [XmlElement("Age")]
    public Dictionary<object, object> Age { get; set; }
}

我有这段代码:

  <PersonenListe>
      <PersonenArray>
        <PersonObjekt>
          <PropertyType>Unknown</PropertyType>
          <ID>0</ID>
          <FriendlyName>Max Man</FriendlyName>
          <City>Capitol City</City>
          <Age>33</Age>
          <Name>
            <item>
              <key>
                <anyType xmlns:q1="http://www.w3.org/2001/XMLSchema" p8:type="q1:string" xmlns:p8="http://www.w3.org/2001/XMLSchema-instance">test1</anyType>
              </key>
              <value>
                <anyType xmlns:q1="http://www.w3.org/2001/XMLSchema" p8:type="q1:string" xmlns:p8="http://www.w3.org/2001/XMLSchema-instance">test2</anyType>
              </value>
            </item>
          </Name>
        </PersonObjekt>
      </PersonenArray>
    </PersonenListe>

How can I clean up it(I want to have code without this namespaces)? maybe using some attributes?


Update:

when I serialize it separetly I get:

<PersonenListe>
  <PersonenArray>
    <PersonObjekt>
      <PropertyType>Unknown</PropertyType>
      <ID>0</ID>
      <FriendlyName>Max Man</FriendlyName>
      <City>Capitol City</City>
      <Age>33</Age>
      <Name />
    </PersonObjekt>
  </PersonenArray>
</PersonenListe>


<?xml version="1.0"?>
<dictionary>
  <item>
    <key>
      <string>test1</string>
    </key>
    <value>
      <string>test2</string>
    </value>
  </item>
</dictionary>

1 个答案:

答案 0 :(得分:0)

example: to Generate Clear XML without namespace

XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("", "");

XmlSerializer serializer = new XmlSerializer(typeof(object));
StringWriter stringWriter = new StringWriter();
using(XmlWriter writer = new XmlTextWriterFormattedNoDeclaration(stringWriter ))
{
    serializer.Serialize(writer, this, ns);
}
string xmlText = stringWriter.ToString();
相关问题