The*_*uru 18 .net c# xsd xml-serialization
我在我的项目中使用xml-serialization来基于xml架构序列化和反序列化对象.我使用xsd工具创建在序列化/反序列化对象时使用的类.
当我在发送之前序列化对象时,我被迫将*Specified属性设置为true,以强制序列化程序序列化所有非类型的属性string
.
有没有办法强制所有属性的序列化,而不必将*Specified属性设置为true?
Tho*_*que 21
该FooSpecified
属性用于控制是否Foo
必须序列化属性.如果您始终要序列化该属性,只需删除该FooSpecified
属性即可.
我知道这是一个古老的问题,但是当您在生成代码的过程中生成.xsd时可能会多次更改,因此其他任何答案(也许除了使用Xsd2Code的建议)都不会真正产生理想的解决方案发布周期。
获得我真正想要的并且仍然使用xsd.exe的一种简单方法是通过一个简单的后处理器运行生成的文件。后处理器的代码如下:
namespace XsdAutoSpecify
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;
class Program
{
static void Main(string[] args)
{
try
{
if (args.Length != 1)
{
throw new ArgumentException("Specify a file name");
}
string fileName = args[0];
Regex regex = new Regex(".*private bool (?<fieldName>.*)Specified;");
IList<string> result = new List<string>();
IDictionary<string, string> edits = new Dictionary<string, string>();
foreach (string line in File.ReadLines(fileName))
{
result.Add(line);
if (line.Contains("public partial class"))
{
// Don't pollute other classes which may contain like-named fields
edits.Clear();
}
else if (regex.IsMatch(line))
{
// We found a "private bool fooSpecified;" line. Add
// an entry to our edit dictionary.
string fieldName = regex.Match(line).Groups["fieldName"].Value;
string lineToAppend = string.Format("this.{0} = value;", fieldName);
string newLine = string.Format(" this.{0}Specified = true;", fieldName);
edits[lineToAppend] = newLine;
}
else if (edits.ContainsKey(line.Trim()))
{
// Use our edit dictionary to add an autospecifier to the foo setter, as follows:
// set {
// this.fooField = value;
// this.fooFieldSpecified = true;
// }
result.Add(edits[line.Trim()]);
}
}
// Overwrite the result
File.WriteAllLines(fileName, result);
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
Environment.Exit(-1);
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
结果是生成类似于以下内容的代码:
[System.Xml.Serialization.XmlAttributeAttribute()]
public barEnum foo {
get {
return this.fooField;
}
set {
this.fooField = value;
this.fooFieldSpecified = true;
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
10736 次 |
最近记录: |