.net 以紧凑、人类可读的方式序列化 XML

.net Serializing XML in a compact, human-readable way

我正在序列化导致此输出的结构:

<NachrichtenKonfiguration>
  <Elemente>
    <Element>
      <Typ>Bool</Typ>
      <Bezeichnung>Gut</Bezeichnung>
    </Element>
    <Element>
      <Typ>Int</Typ>
      <Bezeichnung>Dauer</Bezeichnung>
    </Element>
  </Elemente>
  <Name>Teiledaten</Name>
</NachrichtenKonfiguration>

我希望它是这样的:

<NachrichtenKonfiguration Name="Teiledaten">
  <Elemente>
    <Element Typ="Bool" Bezeichnung="Gut"/>
    <Element Typ="Int" Bezeichnung="Schleifdauer"/>
  </Elemente>
</NachrichtenKonfiguration>

是否可以让 XmlSerialzer / XmlWriter 这样做(使用属性而不是嵌套元素)?

你好,

蒂姆

好的,我明白了,您只需在相应的声明上添加 [XmlAttribute] 标签。

方法如下。如果你有一个叫做 "Person" 的 class 并且你有两个属性在里面,写这样的代码:

[Serializable]
public class Person
{
    [XmlAttribute]
    public int Age;
    [XmlAttribute]
    public string Name;

    public Person()
    {

    }
}

当序列化(将 XmlWriter 设置设置为缩进行)时,上述结构会导致此 xml 代码:

<Person Age="21" Name="Stacky" />