本文整理汇总了C#中System.Xml.Serialization.XmlSerializer类的典型用法代码示例。如果您正苦于以下问题:C# XmlSerializer类的具体用法?C# XmlSerializer怎么用?C# XmlSerializer使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
XmlSerializer类属于System.Xml.Serialization命名空间,在下文中一共展示了XmlSerializer类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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"));
}
}
开发者ID:sillsdev,项目名称:masterinstaller,代码行数:30,代码来源:JavaScriptConverterTests.cs
示例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();
}
开发者ID:Pashahasband,项目名称:SpaceKurs,代码行数:27,代码来源:Program.cs
示例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;
}
开发者ID:robUx4,项目名称:vlc-winrt,代码行数:7,代码来源:BackgroundAudioInterface.cs
示例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;
}
开发者ID:PosauneMaster,项目名称:RecipeMaster_v3,代码行数:27,代码来源:MachineCollection.cs
示例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();
}
开发者ID:BGCX261,项目名称:zjzl-svn-to-git,代码行数:7,代码来源:MaterialList.cs
示例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);
}
}
开发者ID:Jamedjo,项目名称:rocksmith-custom-song-toolkit,代码行数:26,代码来源:Converter.cs
示例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>();
}
}
开发者ID:tym32167,项目名称:dotnetnotepad,代码行数:31,代码来源:FileCompletionDataProvider.cs
示例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;
}
开发者ID:shuainie,项目名称:azure-powershell,代码行数:26,代码来源:PersistentVMHelper.cs
示例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);
}
开发者ID:ChandrakanthBCK,项目名称:xamarin-forms-samples,代码行数:32,代码来源:LoadResourceXml.cs
示例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);
}
}
开发者ID:tikalk,项目名称:fuse.dotnet.mongodb-blogengine,代码行数:26,代码来源:DataStore.cs
示例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);
}
开发者ID:ststeiger,项目名称:XmlToCSharp,代码行数:7,代码来源:When_reading_from_example_file_namespaces.cs
示例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;
}
开发者ID:AdamDotCom,项目名称:adamdotcom-amazon,代码行数:33,代码来源:AmazonApplication.cs
示例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);
}
}
开发者ID:aequitas,项目名称:rocksmith-custom-song-toolkit,代码行数:28,代码来源:Converter.cs
示例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;
}
}
开发者ID:Zeiren92,项目名称:bthmsdevemul,代码行数:26,代码来源:Settings.cs
示例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;
}
开发者ID:Kalnor,项目名称:monodevelop,代码行数:43,代码来源:DiscoveryProtocol.cs
示例16: GetItemPriceById
public Dictionary<int, float> GetItemPriceById(IEnumerable<int> eveId,bool sell=false)
{
var res = new Dictionary<int,float>();
//http://api.eve-central.com/api/marketstat?typeid=34&typeid=35®ionlimit=10000002
var url = new StringBuilder("http://api.eve-central.com/api/marketstat?");
foreach (var id in eveId)
{
url.Append("typeid=").Append(id).Append("&");
}
url.Append("regionlimit=10000002");
using (var cli = new WebClient())
{
var rdr = cli.OpenRead(url.ToString());
var ser = new XmlSerializer(typeof (evec_api));
if (rdr != null)
{
var objectRes = (evec_api)ser.Deserialize(rdr);
foreach (var type in objectRes.marketstat)
{
res[type.id] = sell? type.sell.avg :type.buy.avg;
}
}
}
return res;
}
开发者ID:holinov,项目名称:ZenEveCalc,代码行数:27,代码来源:EveCentalApi.cs
示例17: Execute
public override bool Execute()
{
Log.LogMessage( MessageImportance.Low, "Packing M-Files Application." );
// Make sure the collections are never null.
References = References ?? new ITaskItem[ 0 ];
SourceFiles = SourceFiles ?? new ITaskItem[ 0 ];
DefaultEnvironments = DefaultEnvironments ?? new string[ 0 ];
// Create the application package contents.
var references = References.Select( item => new Reference( item ) ).ToList();
var files = SourceFiles.Select( item => new PackageFile( item ) ).ToList();
var appDef = CreateApplicationDefinition( references, files );
var outputZip = CreatePackage( references, files );
// Serialize the application definition file.
var stream = new MemoryStream();
var serializer = new XmlSerializer( typeof( ApplicationDefinition ) );
serializer.Serialize( stream, appDef );
stream.Flush();
stream.Position = 0;
outputZip.AddEntry( "appdef.xml", stream );
// Save the zip.
outputZip.Save();
return true;
}
开发者ID:Rantanen,项目名称:M-Files-SDK,代码行数:29,代码来源:PackageMFilesApplication.cs
示例18: SerializeObject
public void SerializeObject(string path, SerializableObject objToSerialize)
{
FileStream fstream = File.Open(path, FileMode.Create);
XmlSerializer formatter = new XmlSerializer(typeof(SerializableObject));
formatter.Serialize(fstream, objToSerialize);
fstream.Close();
}
开发者ID:manuylenko,项目名称:-atalogEmployees,代码行数:7,代码来源:SerializerXml.cs
示例19: LoadConfig
internal static Config LoadConfig()
{
string userAppDaraPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
string appName = AppDomain.CurrentDomain.FriendlyName;
while (appName.Contains("."))
{
appName = Path.GetFileNameWithoutExtension(appName);
}
appName += "." + s_configExtension;
string path = Path.Combine(userAppDaraPath, appName);
// search in local folder
if (!File.Exists(path))
return new Config();
using (var fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Read, FileShare.Read))
{
try
{
var configObj = new XmlSerializer(typeof(Config)).Deserialize(fs);
var config = configObj as Config;
if (config != null)
m_lastConfig = config.Copy();
return config;
}
catch (Exception)
{
return new Config();
}
}
}
开发者ID:starkmsu,项目名称:TfsRetrospectiveTool,代码行数:31,代码来源:ConfigManager.cs
示例20: LoadXML
public static Graph LoadXML(FileStream stream)
{
// Convert the object to XML data and put it in the stream.
XmlSerializer serializer = new XmlSerializer(typeof(Graph));
return (Graph)serializer.Deserialize(stream);
}
开发者ID:valkuc,项目名称:xoscillo,代码行数:7,代码来源:Graph.cs
注:本文中的System.Xml.Serialization.XmlSerializer类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论