2

我有以下课程。(SIMModel、Product、Item)

public class SIMModel
{
    public Product Product { get; set; }
}

public class Product
{
    public List<Item> Items { get; set; }
}

public class Item
{
    [XmlAttribute("ID")]
    public String ID { get; set; }
    [XmlAttribute("Name")]
    public String Name { get; set; }

    public Child_Item Child_Item { get; set; }
    public Parent_Item Parent_Item { get; set; }
}

public class Child_Item
{
    [XmlAttribute("ID")]
    public String ID { get; set; }
}

我想制作这个 XML

 <SIMModel>
  <Product>
   <Item ID="N" Name="N-1">
    <Child_Item ID="N-1-1">
   </Item>
  </Proudct>
 </SIMModel>

如何使用上层类制作模拟 XML?我不知道如何包装每个类..

4

1 回答 1

1

I made a simple Serialize method that serializes to string and removes the namespaces.

private static void Main(string[] args)
{
    string result = Serialize(new SIMModel
    {
        Product = new Product
        {
            Items = new List<Item>
            {
                new Item
                {
                    ID = "N",
                    Name = "N-1",
                    Child_Item = new Child_Item {ID = "N-1-1"}
                }
            }
        }
    });
    Console.WriteLine(result);
}

public static string Serialize<T>(T value)
{
    if (value == null)
    {
        return null;
    }
    //Create our own namespaces for the output
    XmlSerializerNamespaces ns = new XmlSerializerNamespaces();

    //Add an empty namespace and empty value
    ns.Add("", "");

    XmlSerializer serializer = new XmlSerializer(typeof (T));

    XmlWriterSettings settings = new XmlWriterSettings
    {
        Encoding = new UnicodeEncoding(false, false),
        Indent = true,
        OmitXmlDeclaration = true
    };

    using (StringWriter textWriter = new StringWriter())
    {
        using (XmlWriter xmlWriter = XmlWriter.Create(textWriter, settings))
        {
            serializer.Serialize(xmlWriter, value, ns);
        }
        return textWriter.ToString();
    }
}

Output:

<SIMModel>
  <Product>
    <Items>
      <Item ID="N" Name="N-1">
        <Child_Item ID="N-1-1" />
      </Item>
    </Items>
  </Product>
</SIMModel>
于 2013-03-05T12:15:41.533 回答