如果我有一个标记为a的类DataContract
和一些标记有DataMember
属性的属性,我可以轻松地将其序列化为XML,但它会创建如下的输出:
<Person>
<Name>John Smith</Name>
<Email>john.smith@acme.com</Email>
<Phone>123-123-1234</Phone>
</Person>
Run Code Online (Sandbox Code Playgroud)
我更喜欢的是属性,比如......
<Person Name="John Smith" Email="john.smith@acme.com" Phone="123-123-1234" />
Run Code Online (Sandbox Code Playgroud)
该DataMember
属性允许我控制名称和顺序,但不能控制它是否被序列化为元素或属性.我环顾四周找到了DataContractFormat
,IXmlSerializable
但我希望有更简单的解决方案.
最简单的方法是什么?
我有以下XML结构.该theElement
元素可以包含theOptionalList
元素,或不:
<theElement attrOne="valueOne" attrTwo="valueTwo">
<theOptionalList>
<theListItem attrA="valueA" />
<theListItem attrA="anotherValue" />
<theListItem attrA="stillAnother" />
</theOptionalList>
</theElement>
<theElement attrOne="anotherOne" attrTwo="anotherTwo" />
Run Code Online (Sandbox Code Playgroud)
什么是表达相应类结构的干净方式?
我很确定以下内容:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
namespace MyNamespace
{
public class TheOptionalList
{
[XmlAttributeAttribute("attrOne")]
public string AttrOne { get; set; }
[XmlAttributeAttribute("attrTwo")]
public string AttrTwo { get; set; }
[XmlArrayItem("theListItem", typeof(TheListItem))]
public TheListItem[] theListItems{ get; set; }
public override string ToString()
{
StringBuilder outText = new StringBuilder();
outText.Append("attrOne = " …
Run Code Online (Sandbox Code Playgroud) 我已经定义了以下类.
Document.cs
public class Document {
// ...
[XmlAttribute]
public string Status { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
DocumentOrder.cs
public class DocumentOrder {
// ...
[XmlAttribute]
public string Name { get; set; }
public List<Document> Documents { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
将此序列化为XML时,我得到:
<DocumentOrder Name="myname">
<Documents>
<Document Status="new"/>
// ...
</Documents>
</DocumentOrder>
Run Code Online (Sandbox Code Playgroud)
但是我想这样做,即Document
成为孩子们的元素DocumentOrder
.
<DocumentOrder Name="myname">
<Document Status="new"/>
<Document Status="new"/>
<Document Status="new"/>
// The document element has other attributes to distinguish...
</DocumentOrder>
Run Code Online (Sandbox Code Playgroud)
我怎样才能做到这一点?