本文整理汇总了C#中System.Xml.Serialization.XmlSerializer类的典型用法代码示例。如果您正苦于以下问题:C# XmlSerializer类的具体用法?C# XmlSerializer怎么用?C# XmlSerializer使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
XmlSerializer类属于System.Xml.Serialization命名空间,在下文中一共展示了XmlSerializer类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: ExistingFeatureInModelIsNotDuplicated
public void ExistingFeatureInModelIsNotDuplicated()
{
var simpleScript =
@"// Fills in details for download packages automatically.
// This instance created AUTOMATICALLY during a previous run.
function AutomatePackages()
{
SetElement(""FlavorName1"", ""NAME"");
SetElement(""FlavorUrl1"", ""URL"");
NextStage();
NextStage();
}";
var configuration = new ConfigurationModel();
configuration.Flavors = new List<ConfigurationModel.FlavorOptions> { new ConfigurationModel.FlavorOptions { FlavorName = "NAME"}};
var scriptFile = Path.Combine(TestFolder, "test.js");
var installerFile = Path.Combine(TestFolder, "installer.xml");
File.WriteAllText(scriptFile, simpleScript);
configuration.FileLocation = installerFile;
configuration.Save();
JavaScriptConverter.ConvertJsToXml(scriptFile, installerFile);
var serializer = new XmlSerializer(typeof(ConfigurationModel));
using (var textReader = new StreamReader(installerFile))
{
var model = (ConfigurationModel)serializer.Deserialize(textReader);
Assert.That(model.Flavors, Is.Not.Null);
Assert.That(model.Flavors.Count, Is.EqualTo(1));
Assert.That(model.Flavors.First().FlavorName, Is.EqualTo("NAME"));
Assert.That(model.Flavors.First().DownloadURL, Is.EqualTo("URL"));
}
}
示例2: SendFileInfo
public static void SendFileInfo()
{
// Получаем тип и расширение файла
fileDet.FILETYPE = fs.Name.Substring((int)fs.Name.Length - 3, 3);
// Получаем длину файла
fileDet.FILESIZE = fs.Length;
XmlSerializer fileSerializer = new XmlSerializer(typeof(FileDetails));
MemoryStream stream = new MemoryStream();
// Сериализуем объект
fileSerializer.Serialize(stream, fileDet);
// Считываем поток в байты
stream.Position = 0;
Byte[] bytes = new Byte[stream.Length];
stream.Read(bytes, 0, Convert.ToInt32(stream.Length));
Console.WriteLine("Отправка деталей файла...");
// Отправляем информацию о файле
sender.Send(bytes, bytes.Length, endPoint);
stream.Close();
}
示例3: DeserializeObjectAudioTrack
public static BackgroundTrackItem DeserializeObjectAudioTrack(this string s)
{
XmlSerializer xmlSerializer = new XmlSerializer(typeof(BackgroundTrackItem));
StringReader textReader = new StringReader(s);
return xmlSerializer.Deserialize(textReader) as BackgroundTrackItem;
}
示例4: LoadSettings
public static MachineCollection LoadSettings(string path)
{
MachineCollection machineCollection;
if (File.Exists(path))
{
XmlSerializer deserializer = new XmlSerializer(typeof(MachineCollection));
using (TextReader textReader = new StreamReader(path))
{
try
{
machineCollection = (MachineCollection)deserializer.Deserialize(textReader);
machineCollection.Initialize();
}
catch (System.Exception ex)
{
machineCollection = new MachineCollection();
Log.LogError("", ex);
}
}
}
else
{
machineCollection = new MachineCollection();
}
return machineCollection;
}
示例5: Serialize
public static string Serialize(MaterialList mats)
{
StringWriter sw = new StringWriter();
XmlSerializer ser = new XmlSerializer(typeof(MaterialList));
ser.Serialize(sw, mats);
return sw.ToString();
}
示例6: Convert
public void Convert(string inputFileName, string outputFileName)
{
var deser = new XmlSerializer(typeof(Song));
Song zigSong;
using (FileStream stream = new FileStream(inputFileName, FileMode.Open))
{
zigSong = (Song)deser.Deserialize(stream);
}
var guitarTrack = GetTrack(zigSong);
if (guitarTrack == null)
{
throw new Exception("Couldn't find a guitar track");
}
var rsSong = new RsSong();
AddSongMetadata(rsSong, zigSong);
AddEbeats(rsSong, zigSong);
AddNotes(rsSong, zigSong);
deser = new XmlSerializer(typeof(RsSong));
using (FileStream stream = new FileStream(outputFileName, FileMode.Create))
{
deser.Serialize(stream, rsSong);
}
}
示例7: GetData
private IEnumerable<ICompletionData> GetData(string highlightingName)
{
try
{
var result = new List<ICompletionData>();
var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Intellisense", "Keywords", "options.xml");
using (var sr = new StreamReader(path))
{
var ser = new XmlSerializer(typeof(List<KeywordsFileOption>));
var ops = (List<KeywordsFileOption>)ser.Deserialize(sr);
var filePath = Path.Combine(Application.StartupPath, "Intellisense", "Keywords",
ops
.Where(x => string.Compare(x.HighlightingName, highlightingName) == 0)
.Select(x => x.Filename)
.FirstOrDefault() ?? string.Empty);
if (File.Exists(filePath))
{
var w = GetWords(filePath);
result.AddRange(w);
}
}
return result;
}
catch (Exception)
{
// TODO: приделать логирование
return new List<ICompletionData>();
}
}
示例8: LoadStateFromFile
public static PersistentVM LoadStateFromFile(string filePath)
{
if (!File.Exists(filePath))
{
throw new ArgumentException(Resources.MissingPersistentVMFile, "filePath");
}
XmlAttributeOverrides overrides = new XmlAttributeOverrides();
XmlAttributes ignoreAttrib = new XmlAttributes();
ignoreAttrib.XmlIgnore = true;
overrides.Add(typeof(DataVirtualHardDisk), "MediaLink", ignoreAttrib);
overrides.Add(typeof(DataVirtualHardDisk), "SourceMediaLink", ignoreAttrib);
overrides.Add(typeof(OSVirtualHardDisk), "MediaLink", ignoreAttrib);
overrides.Add(typeof(OSVirtualHardDisk), "SourceImageName", ignoreAttrib);
var serializer = new System.Xml.Serialization.XmlSerializer(typeof(PersistentVM), overrides, new Type[] { typeof(NetworkConfigurationSet) }, null, null);
PersistentVM role = null;
using (var stream = new FileStream(filePath, FileMode.Open))
{
role = serializer.Deserialize(stream) as PersistentVM;
}
return role;
}
示例9: LoadResourceXml
public LoadResourceXml ()
{
#region How to load an XML file embedded resource
var assembly = typeof(LoadResourceText).GetTypeInfo().Assembly;
Stream stream = assembly.GetManifestResourceStream("WorkingWithFiles.PCLXmlResource.xml");
List<Monkey> monkeys;
using (var reader = new System.IO.StreamReader (stream)) {
var serializer = new XmlSerializer(typeof(List<Monkey>));
monkeys = (List<Monkey>)serializer.Deserialize(reader);
}
#endregion
var listView = new ListView ();
listView.ItemsSource = monkeys;
Content = new StackLayout {
Padding = new Thickness (0, 20, 0, 0),
VerticalOptions = LayoutOptions.StartAndExpand,
Children = {
new Label { Text = "Embedded Resource XML File (PCL)",
FontSize = Device.GetNamedSize (NamedSize.Medium, typeof(Label)),
FontAttributes = FontAttributes.Bold
}, listView
}
};
// NOTE: use for debugging, not in released app code!
//foreach (var res in assembly.GetManifestResourceNames())
// System.Diagnostics.Debug.WriteLine("found resource: " + res);
}
示例10: SaveToDataStore
public override void SaveToDataStore(BlogEngine.Core.DataStore.ExtensionType exType, string exId, object settings)
{
XmlSerializer xs = new XmlSerializer(settings.GetType());
string objectXML = string.Empty;
using (StringWriter sw = new StringWriter())
{
xs.Serialize(sw, settings);
objectXML = sw.ToString();
}
using (var mongo = new MongoDbWr())
{
var coll = mongo.BlogDB.GetCollection("DataStoreSettings");
Document spec = new Document();
spec["ExtensionType"] = exType;
spec["ExtensionId"] = exId;
var res = new Document();
res["Settings"] = objectXML;
res["ExtensionType"] = exType;
res["ExtensionId"] = exId;
coll.Update(res, spec, UpdateFlags.Upsert);
}
}
示例11: When_reading_from_example_file_namespaces
public When_reading_from_example_file_namespaces()
{
var readAllText = File.OpenRead(Path.Combine(Environment.CurrentDirectory, "..\\..\\..\\ExamplesFiles\\namespaces.xml"));
var xmlSerializer = new XmlSerializer(typeof(root));
root = (root)xmlSerializer.Deserialize(readAllText);
}
示例12: Save
public bool Save()
{
IAmazonResponse amazonResponse = amazonFactory.GetResponse();
XmlSerializer serializer;
TextWriter writer;
try
{
if (amazonResponse.Errors.Count != 0)
{
serializer = new XmlSerializer(typeof (List<string>));
writer = new StreamWriter(fileParameters.ErrorFileNameAndPath);
serializer.Serialize(writer, amazonResponse.Errors);
writer.Close();
}
serializer = new XmlSerializer(typeof (List<Review>));
writer = new StreamWriter(fileParameters.ReviewFileNameAndPath);
serializer.Serialize(writer, amazonResponse.Reviews);
writer.Close();
serializer = new XmlSerializer(typeof (List<Product>));
writer = new StreamWriter(fileParameters.ProductFileNameAndPath);
serializer.Serialize(writer, amazonResponse.Products);
writer.Close();
}
catch
{
return false;
}
return true;
}
示例13: Convert
public void Convert(string inputFileName, string outputFileName)
{
var deser = new XmlSerializer(typeof(ZpeSong));
ZpeSong zigSong;
using (FileStream stream = new FileStream(inputFileName, FileMode.Open))
{
zigSong = (ZpeSong)deser.Deserialize(stream);
}
if (zigSong.PueVersion != 46)
throw new Exception("Incompatable version of Ziggy Pro Editor XML");
var guitarTrack = GetTrack(zigSong);
if (guitarTrack == null)
{
throw new Exception("Couldn't find a guitar track");
}
var rsSong = new Song();
AddSongMetadata(rsSong, zigSong);
AddEbeats(rsSong, zigSong);
AddNotes(rsSong, zigSong);
using (FileStream stream = new FileStream(outputFileName, FileMode.Create))
{
rsSong.Serialize(stream, true);
}
}
示例14: Deserialize
public void Deserialize(string settingsPath)
{
XmlSerializer serializer = new XmlSerializer(typeof(Settings));
TextReader reader = null;
Settings settings = null;
try
{
reader = new StreamReader(settingsPath + "\\" + FILE_NAME);
settings = (Settings)serializer.Deserialize(reader);
}
catch {;}
finally
{
if (reader != null)
{
reader.Close();
}
}
if (settings != null)
{
this.DeviceLogging = settings.DeviceLogging;
this.DesktopLogging = settings.DesktopLogging;
this.CommLogging = settings.CommLogging;
}
}
示例15: ReadAllUseBasePath
/// <summary>
/// Reads in a file containing a map of saved discovery documents populating the Documents and References properties,
/// with discovery documents, XML Schema Definition (XSD) schemas, and service descriptions referenced in the file.
/// </summary>
/// <param name="topLevelFilename">Name of file to read in, containing the map of saved discovery documents.</param>
/// <returns>
/// A DiscoveryClientResultCollection containing the results found in the file with the map of saved discovery documents.
/// The file format is a DiscoveryClientProtocol.DiscoveryClientResultsFile class serialized into XML; however, one would
/// typically create the file using only the WriteAll method or Disco.exe.
/// </returns>
public DiscoveryClientResultCollection ReadAllUseBasePath(string topLevelFilename)
{
string basePath = (new FileInfo(topLevelFilename)).Directory.FullName;
var sr = new StreamReader (topLevelFilename);
var ser = new XmlSerializer (typeof (DiscoveryClientResultsFile));
var resfile = (DiscoveryClientResultsFile) ser.Deserialize (sr);
sr.Close ();
foreach (DiscoveryClientResult dcr in resfile.Results)
{
// Done this cause Type.GetType(dcr.ReferenceTypeName) returned null
Type type;
switch (dcr.ReferenceTypeName)
{
case "System.Web.Services.Discovery.ContractReference":
type = typeof(ContractReference);
break;
case "System.Web.Services.Discovery.DiscoveryDocumentReference":
type = typeof(DiscoveryDocumentReference);
break;
default:
continue;
}
var dr = (DiscoveryReference) Activator.CreateInstance(type);
dr.Url = dcr.Url;
var fs = new FileStream (Path.Combine(basePath, dcr.Filename), FileMode.Open, FileAccess.Read);
Documents.Add (dr.Url, dr.ReadDocument (fs));
fs.Close ();
References.Add (dr.Url, dr);
}
return resfile.Results;
}