XmlSerializer:格式化标签

时间:2012-07-12 11:17:11

标签: c# .net xml xml-serialization

我使用.NET XmlSerializer简单地序列化了具有Items作为集合的Person;

class Item
{
   Name
   Price
}

class Person
{
   Name
   List Items<Item>
}

Everthing fine ...我使用XmlWriterSettings来缩进我的xml文件。输出是:

   <?xml version="1.0" encoding="utf-8"?>
<Person xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <name>TestName</name>
  <Items>
    <Item>
      <name>one</name>
      <price>0</price>
    </Item>
    <Item>
      <name>two</name>
      <price>1</price>
    </Item>
  </Items>
</Viewport>

但我想要的是:

<?xml version="1.0" encoding="utf-8"?>
<Person xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <name>TestName</name>
  <Items>
     <Item name="one" price="0" />
     <Item name="two" price="1" />
  </Items>
</Viewport>

很快而不是

<Item>
      <name>one</name>
      <price>0</price>
 </Item>

我想把xml写为

<Item name="one" price="0" />

我如何在.NET(C#)中完成它?

2 个答案:

答案 0 :(得分:2)

class Item
{
    [System.Xml.Serialization.XmlAttributeAttribute("name")]
    string Name;
    [System.Xml.Serialization.XmlAttributeAttribute("price")]
    string Price;
}

答案 1 :(得分:0)

装饰你的Name&amp; Price

XmlAttribute个属性