相关疑难解决方法(0)

如何控制.NET DataContract序列化,以便它使用XML属性而不是元素?

如果我有一个标记为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但我希望有更简单的解决方案.

最简单的方法是什么?

.net serialization xml-serialization datacontract

16
推荐指数
2
解决办法
3万
查看次数

如何为可选的XML元素装饰/定义类成员以与XmlSerializer一起使用?

我有以下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)

c# xmlserializer

5
推荐指数
2
解决办法
2万
查看次数

使用XmlSerializer序列化List <>

我已经定义了以下类.

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)

我怎样才能做到这一点?

c# xml-serialization

5
推荐指数
1
解决办法
95
查看次数