本文整理汇总了C#中System.Xml.Serialization.XmlSerializer.Deserialize方法的典型用法代码示例。如果您正苦于以下问题:C# XmlSerializer.Deserialize方法的具体用法?C# XmlSerializer.Deserialize怎么用?C# XmlSerializer.Deserialize使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Xml.Serialization.XmlSerializer
的用法示例。
在下文中一共展示了XmlSerializer.Deserialize方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: WMIBMySQL
public WMIBMySQL()
{
string file = Variables.ConfigurationDirectory + Path.DirectorySeparatorChar + "unwrittensql.xml";
Core.RecoverFile(file);
if (File.Exists(file))
{
Syslog.WarningLog("There is a mysql dump file from previous run containing mysql rows that were never successfuly inserted, trying to recover them");
XmlDocument document = new XmlDocument();
using (TextReader sr = new StreamReader(file))
{
document.Load(sr);
using (XmlNodeReader reader = new XmlNodeReader(document.DocumentElement))
{
XmlSerializer xs = new XmlSerializer(typeof(Unwritten));
Unwritten un = (Unwritten)xs.Deserialize(reader);
lock (unwritten.PendingRows)
{
unwritten.PendingRows.AddRange(un.PendingRows);
}
}
}
}
Thread reco = new Thread(Exec) {Name = "MySQL/Recovery"};
Core.ThreadManager.RegisterThread(reco);
reco.Start();
}
示例2: GetSettings
/// <summary>
/// Retreaves StringDictionary object from database or file system
/// </summary>
/// <param name="extensionType">
/// Extension Type
/// </param>
/// <param name="extensionId">
/// Extension Id
/// </param>
/// <returns>
/// StringDictionary object as Stream
/// </returns>
public object GetSettings(ExtensionType extensionType, string extensionId)
{
SerializableStringDictionary ssd;
var sd = new StringDictionary();
var serializer = new XmlSerializer(typeof(SerializableStringDictionary));
if (Section.DefaultProvider == "XmlBlogProvider")
{
var stm = (Stream)BlogService.LoadFromDataStore(extensionType, extensionId);
if (stm != null)
{
ssd = (SerializableStringDictionary)serializer.Deserialize(stm);
stm.Close();
sd = ssd;
}
}
else
{
var o = BlogService.LoadFromDataStore(extensionType, extensionId);
if (!string.IsNullOrEmpty((string)o))
{
using (var reader = new StringReader((string)o))
{
ssd = (SerializableStringDictionary)serializer.Deserialize(reader);
}
sd = ssd;
}
}
return sd;
}
示例3: Generate
public void Generate(Package sourcePackage, Package targetPackage, FileInfo outputFile)
{
var serializer = new XmlSerializer(typeof(DataSchemaModel));
var uri = PackUriHelper.CreatePartUri(new Uri("/replication.xml", UriKind.Relative));
var sourceModel = (DataSchemaModel)serializer.Deserialize(sourcePackage.GetPart(uri).GetStream());
var targetModel = (DataSchemaModel)serializer.Deserialize(targetPackage.GetPart(uri).GetStream());
var outputFileSql = new List<string>();
foreach (var publicationToCreate in sourceModel.Model.Elements.Except(targetModel.Model.Elements, x => x.Name))
{
var createPublicationStep = new CreatePublicationStep(publicationToCreate);
outputFileSql.AddRange(createPublicationStep.GenerateTSQL());
}
foreach (var publicationToAlter in sourceModel.Model.Elements.Intersect(targetModel.Model.Elements, x => x.Name))
{
var sqlPublicationComparer = new SqlPublicationComparer();
var matchingPublicationInTarget = targetModel.Model.Elements.Single(x => x.Name == publicationToAlter.Name);
var alterPublicationStep = new AlterPublicationStep(sqlPublicationComparer.Compare(publicationToAlter, matchingPublicationInTarget));
outputFileSql.AddRange(alterPublicationStep.GenerateTSQL());
}
foreach (var publicationToDrop in targetModel.Model.Elements.Except(sourceModel.Model.Elements, x => x.Name))
{
var dropPublicationStep = new DropPublicationStep(publicationToDrop);
outputFileSql.AddRange(dropPublicationStep.GenerateTSQL());
}
}
示例4: TestDeserializedObjects
public void TestDeserializedObjects()
{
XmlSerializer ser = new XmlSerializer(typeof(OpenSearchDescription));
// Base OpenSearch description document
OpenSearchDescription osd1 = (OpenSearchDescription)ser.Deserialize(XmlReader.Create("../Samples/ParametersTest1.osd.xml"));
OpenSearchParameterValueSet vs1 = OpenSearchParameterValueSet.FromOpenSearchDescription(osd1, "application/atom+xml");
// Equivalent OpenSearch description document where parameter names are changed
OpenSearchDescription osd2 = (OpenSearchDescription)ser.Deserialize(XmlReader.Create("../Samples/ParametersTest2.osd.xml"));
OpenSearchParameterValueSet vs2 = OpenSearchParameterValueSet.FromOpenSearchDescription(osd2, "application/atom+xml");
// Equivalent OpenSearch description document where parameter names and namespace prefixes are changed
OpenSearchDescription osd3 = (OpenSearchDescription)ser.Deserialize(XmlReader.Create("../Samples/ParametersTest3.osd.xml"));
OpenSearchParameterValueSet vs3 = OpenSearchParameterValueSet.FromOpenSearchDescription(osd3, "application/atom+xml");
// Set values
vs1.SetValueByIdentifier("http://a9.com/-/opensearch/extensions/geo/1.0/", "box", "5,5,6,6");
vs1.SetValueByIdentifier("searchTerms", "test search");
// Verify search query string correctness
Assert.AreEqual("format=atom&count=&startPage=&startIndex=&q=test search&start=&stop=&trel=&bbox=5,5,6,6&uid=", vs1.GetQueryString(true));
Assert.AreEqual("format=atom&q=test search&bbox=5,5,6,6", vs1.GetQueryString(false));
// Translate value set by basic identifier matching
vs2.TranslateFrom(vs1);
Assert.AreEqual("format=atom&count2=&startPage2=&startIndex2=&q2=test search&start2=&stop2=&trel2=&bbox2=5,5,6,6&uid2=", vs2.GetQueryString(true));
Assert.AreEqual("format=atom&q2=test search&bbox2=5,5,6,6", vs2.GetQueryString(false));
// Translate value set by advanced identifier matching (verify namespace URIs)
vs3.TranslateFrom(vs1, true);
Assert.AreEqual("format=atom&count3=&startPage3=&startIndex3=&q3=test search&start3=&stop3=&trel3=&bbox3=5,5,6,6&uid3=", vs3.GetQueryString(true));
Assert.AreEqual("format=atom&q3=test search&bbox3=5,5,6,6", vs3.GetQueryString(false));
}
示例5: Resume
public void Resume()
{
string fname = "snake.xml";
if (sign == '@')
fname = "food.xml";
if (sign == '#')
fname = "wall.xml";
string path = @"C:\Users\Zhandos\Documents\Visual Studio 2012\Projects\SNAKE\SNAKE\SNAKE\xml\" + fname;
FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);
XmlSerializer xs = new XmlSerializer(GetType());
if (sign == 'o')
{
Game.snake.body.Clear();
Game.snake = xs.Deserialize(fs) as Snake;
}
if (sign == '#')
{
Game.wall.body.Clear();
Game.wall = xs.Deserialize(fs) as Wall;
}
if (sign == '@')
{
Game.food.body.Clear();
Game.food = xs.Deserialize(fs) as Food;
}
fs.Close();
}
示例6: SendAsync
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
var orderSerializer = new XmlSerializer(typeof(PurchaseOrderType));
var ordersSerializer = new XmlSerializer(typeof(PurchaseOrdersType));
var responseMessage = new HttpResponseMessage();
var stream = new MemoryStream();
var localPath = request.RequestUri.LocalPath;
// GET /orders/notshipped
if (localPath.EndsWith("/orders/notshipped"))
ordersSerializer.Serialize(stream, repository.GetNotShipped());
// GET /orders/shipped
if (localPath.EndsWith("/orders/shipped"))
ordersSerializer.Serialize(stream, repository.GetShipped());
// POST /orders/{id}/ship
if (localPath.EndsWith("/ship") && request.Method == HttpMethod.Post)
{
var shipUrl = localPath;
var shipId = shipUrl.Replace("/api/orders/", string.Empty).Replace("/ship", string.Empty);
var shipOrder = repository.Get(shipId);
shipOrder.shipped = true;
repository.Update(shipOrder);
}
// POST /orders
if (localPath.EndsWith("/orders") && request.Method == HttpMethod.Post)
{
var result = request.Content.ReadAsByteArrayAsync().GetAwaiter().GetResult();
var xml = Encoding.UTF8.GetString(result);
var newOrder = (PurchaseOrderType)orderSerializer.Deserialize(new StringReader(xml));
repository.Add(newOrder);
}
// PUT /orders
if (request.Method == HttpMethod.Put)
{
var result = request.Content.ReadAsByteArrayAsync().GetAwaiter().GetResult();
var xml = Encoding.UTF8.GetString(result);
var orderToUpdate = (PurchaseOrderType)orderSerializer.Deserialize(new StringReader(xml));
repository.Update(orderToUpdate);
}
if (request.Method == HttpMethod.Get && !localPath.EndsWith("/orders") && !localPath.EndsWith("/orders/") && !localPath.EndsWith("shipped"))
{
// GET /orders/{id}
var url = localPath;
var id = url.Replace("/api/orders/", string.Empty);
var order = repository.Get(id);
orderSerializer.Serialize(stream, order);
}
var content = Encoding.UTF8.GetString(stream.GetBuffer());
content = content.Substring(content.IndexOf(Environment.NewLine) + 1);
responseMessage.Content = new StringContent(content, Encoding.UTF8, "application/xml");
return Task.FromResult(responseMessage);
}
示例7: HopsRepository
public HopsRepository()
{
if (hopses == null)
{
Assembly assembly = typeof(HopsRepository).Assembly;
XmlSerializer serializer = new XmlSerializer(typeof(HopsData));
HopsData loadedObject;
var path = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
HopsDataLocalPath = String.Format("{0}\\{1}\\{2}", path, assembly.GetName().Name, HOPS_DATA_FILENAME);
if (File.Exists(HopsDataLocalPath))
{
FileStream loadStream = new FileStream(HopsDataLocalPath, FileMode.Open, FileAccess.Read);
loadedObject = (HopsData)serializer.Deserialize(loadStream);
loadStream.Close();
}
else
{
var resourceName = "WpfApplication1.Resources.hopses.xml";
var stream =
assembly.GetManifestResourceStream(resourceName);
var reader = new System.IO.StreamReader(stream);
loadedObject = (HopsData)serializer.Deserialize(reader);
}
hopses = loadedObject.Hopses;
}
}
示例8: Resume
public void Resume(Game game)
{
string fileName = "";
switch (sign)
{
case '#':
fileName = "wall.xml";
break;
case '$':
fileName = "food.xml";
break;
case 'o':
fileName = "snake.xml";
break;
}
FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
XmlSerializer xs = new XmlSerializer(this.GetType());
switch (sign)
{
case '#':
game.wall.body.Clear();
game.wall = xs.Deserialize(fs) as Wall;
break;
case '$':
game.food.body.Clear();
game.food = xs.Deserialize(fs) as Food;
break;
case 'o':
game.snake.body.Clear();
game.snake = xs.Deserialize(fs) as Snake;
break;
}
fs.Close();
}
示例9: Resume
public void Resume()
{
string FileName = "";
if (sign == 'o')
FileName = "snake.xml";
if (sign == '*')
FileName = "food.xml";
if (sign == '=')
FileName = "wall.xml";
FileStream fs = new FileStream(FileName, FileMode.Open, FileAccess.ReadWrite);
XmlSerializer xs = new XmlSerializer(GetType());
//BinaryFormatter bf = new BinaryFormatter();
if (sign == '*')
Game.food = xs.Deserialize(fs) as Food;
if (sign == '=')
Game.wall = xs.Deserialize(fs) as Wall;
if (sign == 'o')
Game.snake = xs.Deserialize(fs) as Snake;
fs.Close();
}
示例10: GetSettings
/// <summary>
/// Retreaves StringDictionary object from database or file system
/// </summary>
/// <param name="exType">Extension Type</param>
/// <param name="exId">Extension Id</param>
/// <returns>StringDictionary object as Stream</returns>
public object GetSettings(ExtensionType exType, string exId)
{
SerializableStringDictionary ssd = null;
StringDictionary sd = new StringDictionary();
XmlSerializer serializer = new XmlSerializer(typeof(SerializableStringDictionary));
if (_section.DefaultProvider == "XmlTrainProvider")
{
Stream stm = (Stream)TrainService.LoadFromDataStore(exType, exId);
if (stm != null)
{
ssd = (SerializableStringDictionary)serializer.Deserialize(stm);
stm.Close();
sd = (StringDictionary)ssd;
}
}
else
{
object o = TrainService.LoadFromDataStore(exType, exId);
if (!string.IsNullOrEmpty((string)o))
{
using (StringReader reader = new StringReader((string)o))
{
ssd = (SerializableStringDictionary)serializer.Deserialize(reader);
}
sd = (StringDictionary)ssd;
}
}
return sd;
}
示例11: Main
/// <summary>
/// プログラムのエントリーポイント。
/// </summary>
/// <param name="args">コマンドライン引数。</param>
public static void Main(string[] args)
{
var password = "Easy#Password";
var serializer = new XmlSerializer(typeof(UserMan));
UserMan userMan;
// XML ファイルの内容をオブジェクトに読み込みます。
using (var userManStream = new FileStream("UserMan.xml", FileMode.Open, FileAccess.Read))
{
userMan = serializer.Deserialize(userManStream) as UserMan;
foreach (var user in userMan.UserList)
{
Console.WriteLine("User ID: {0}", user.UserID);
Console.WriteLine("User Name: {0}", user.UserName);
}
}
// オブジェクトを暗号化して保存します。
using (var encryptor = new Encryptor("userMan.xml.enc", password))
{
serializer.Serialize(encryptor.EncryptStream, userMan);
}
// 暗号化したファイルを復号化して、オブジェクトに読み込みます。
using (var decryptor = new Decryptor("UserMan.xml.enc", password))
{
UserMan decryptedUserMan = serializer.Deserialize(decryptor.DecryptStream) as UserMan;
foreach (var user in decryptedUserMan.UserList)
{
Console.WriteLine("User ID: {0}", user.UserID);
Console.WriteLine("User Name: {0}", user.UserName);
}
}
}
示例12: Main
public static void Main(string[] args)
{
XmlSerializer x = new XmlSerializer(typeof(Configuration));
Configuration Cf;
string xmlfile;
string shefile;
if (args.Length == 2)
{
if (Path.GetExtension(args[0]).ToLower() == ".xml")
{
xmlfile = args[0];
shefile = args[1];
}
else
{
xmlfile = args[1];
shefile = args[0];
}
using (FileStream fs = new FileStream(xmlfile, System.IO.FileMode.Open))
Cf = (Configuration)x.Deserialize(fs);
Cf.SheFile = shefile;
}
else
Cf = (Configuration)x.Deserialize(new FileStream(args[0], System.IO.FileMode.Open));
Controller C = new Controller(Cf);
C.Run();
}
示例13: RunAsync
static async Task RunAsync()
{
try
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(s_wepApiServer);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
MitchellClaimType claim = null;
HttpResponseMessage response;
// Get all Claims
List<MitchellClaimType> claims = Claims(client).Result;
XmlSerializer xmlSerializer = new XmlSerializer(typeof(MitchellClaimType));
string[] files = Directory.GetFiles("../../NewClaims", "*.xml");
// Add New Claims
foreach (string fileName in files)
{
using (StreamReader reader = new StreamReader(fileName))
{
claim = (MitchellClaimType)xmlSerializer.Deserialize(reader);
response = await client.PostAsJsonAsync<MitchellClaimType>(autoClaimApi, claim).ContinueWith((postTask) => postTask.Result.EnsureSuccessStatusCode());
}
}
claims = Claims(client).Result;
claim = Claim(client, claims.First().MitchellClaimTypeId).Result;
// Update Claims
files = Directory.GetFiles("../../ClaimUpdates", "*.xml");
foreach (string fileName in files)
{
using (StreamReader reader = new StreamReader(fileName))
{
MitchellClaimType claimUpdates = (MitchellClaimType)xmlSerializer.Deserialize(reader);
claim = (from c in claims where c.ClaimNumber == claimUpdates.ClaimNumber select c).FirstOrDefault();
if (claimUpdates.MitchellClaimTypeId != claim.MitchellClaimTypeId)
claimUpdates.MitchellClaimTypeId = claim.MitchellClaimTypeId;
// more to do response = await client.PutAsJsonAsync<MitchellClaimType>(autoClaimApi + "/" + claim.MitchellClaimTypeId, claimUpdates).ContinueWith((postTask) => postTask.Result.EnsureSuccessStatusCode());
}
}
// Read a Claim
claim = Claim(client, claim.MitchellClaimTypeId).Result;
// Delete a claim
// more to do response = await client.DeleteAsync(autoClaimApi + "/" + claim.MitchellClaimTypeId).ContinueWith((postTask) => postTask.Result.EnsureSuccessStatusCode());
claim = Claim(client, claim.MitchellClaimTypeId).Result;
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
示例14: ExecuteAsync
public override async Task ExecuteAsync(Update update, Dictionary<string, string> parsedMessage)
{
var responseStream = new StreamReader(await GetCurrencyRates());
var xmlDeserializer = new XmlSerializer(typeof(CurrencyContainerXml.DailyExRates));
var currencyContainer = new CurrencyContainerXml() { DailyRates = xmlDeserializer.Deserialize(responseStream) as CurrencyContainerXml.DailyExRates };
// Get data for previous date for comparison
if (_previousDayCurrencyContainer == null ||
DateTime.ParseExact(_previousDayCurrencyContainer.DailyRates.Date, "MM/dd/yyyy", null).AddDays(1) !=
DateTime.ParseExact(currencyContainer.DailyRates.Date, "MM/dd/yyyy", null))
{
var ondate = DateTime.ParseExact(currencyContainer.DailyRates.Date, "MM/dd/yyyy", null).AddDays(-1);
// Rates do not update on weekend (at least here, duh)
if (ondate.DayOfWeek == DayOfWeek.Sunday)
{
ondate = ondate.AddDays(-2);
}
var ondatestring = ondate.ToString(@"MM\/dd\/yyyy");
responseStream = new StreamReader(await GetCurrencyRates(OnDateParam + ondatestring));
_previousDayCurrencyContainer = new CurrencyContainerXml() { DailyRates = xmlDeserializer.Deserialize(responseStream) as CurrencyContainerXml.DailyExRates };
}
var sb = new StringBuilder();
sb.Append("Курсы валют на ");
sb.AppendLine(DateTime.ParseExact(currencyContainer.DailyRates.Date, "MM/dd/yyyy", null).ToShortDateString());
sb.Append("По отношению к ");
sb.AppendLine(DateTime.ParseExact(_previousDayCurrencyContainer.DailyRates.Date, "MM/dd/yyyy", null).ToShortDateString());
sb.AppendLine();
List<string> currenciesList = new List<string>();
if (parsedMessage.ContainsKey("message"))
{
var names = parsedMessage["message"].Split(',').ToList();
currenciesList.AddRange(names.Select(cname => cname.ToUpper()));
}
if (currenciesList.Count == 0)
currenciesList = _defaultCurrenciesList;
foreach (var currency in currencyContainer.DailyRates.Currency.Where(x => currenciesList.Contains(x.CharCode)))
{
sb.Append(currency.CharCode + ": " + currency.Rate);
if (_previousDayCurrencyContainer != null)
{
var diff = currency.Rate -
_previousDayCurrencyContainer.DailyRates.Currency.First(
x => x.CharCode == currency.CharCode).Rate;
sb.Append(" _(");
sb.Append(diff > 0 ? "+" : "-");
sb.Append(Math.Abs(diff));
sb.Append(")_");
}
sb.AppendLine();
}
await Bot.SendTextMessage(update.Message.Chat.Id, sb.ToString(), false, update.Message.MessageId, null, true);
}
示例15: Resume
public void Resume()
{
Type t = this.GetType();
FileStream fs = new FileStream(string.Format("{0}.xml", t.Name), FileMode.Open, FileAccess.Read);
XmlSerializer xs = new XmlSerializer(t);
if (t == typeof(Snake)) Game.s = xs.Deserialize(fs) as Snake;
if (t == typeof(Food)) Game.f = xs.Deserialize(fs) as Food;
if (t == typeof(Wall)) Game.w = xs.Deserialize(fs) as Wall;
fs.Close();
}