本文整理匯總了C#中System.Xml.XmlDocument.ToXDocument方法的典型用法代碼示例。如果您正苦於以下問題:C# XmlDocument.ToXDocument方法的具體用法?C# XmlDocument.ToXDocument怎麽用?C# XmlDocument.ToXDocument使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類System.Xml.XmlDocument
的用法示例。
在下文中一共展示了XmlDocument.ToXDocument方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的C#代碼示例。
示例1: Load
public void Load(String fromPath)
{
var xmlDocument = new XmlDocument();
xmlDocument.Load(fromPath);
loadFile = xmlDocument.ToXDocument();
Practice.ClearCurrent();
PreloadAllEntityGroups();
LoadPracticeSettings();
LoadSlides();
LoadObjects();
LoadActions();
}
示例2: Insert
private static void Insert()
{
string url = "http://www.moneytrackin.com/api/rest/insertTransaction?project=&description=lorem+ipsum&amount=-123&date=2013-04-20&tags=food";
bool success = false;
string errorMessage = String.Empty;
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.Method = "GET";
request.Headers.Add("Authorization", "Basic yourkeygoeshere");
try {
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse) {
string xmlResponse;
using (StreamReader reader = new StreamReader(response.GetResponseStream())) {
xmlResponse = reader.ReadToEnd();
}
var doc = new XmlDocument();
doc.LoadXml(xmlResponse);
var xdoc = doc.ToXDocument();
var code = (string)xdoc.Root.Attribute("code");
var query = from c in xdoc.Descendants("error")
select new {
ErrorMessage = (string)c.Value
};
success = code.ToLower() == "done";
errorMessage = query.FirstOrDefault() != null ? query.FirstOrDefault().ErrorMessage : "Undefined error.";
}
//_logger.InfoFormat("Sent email for request commitment ID {0}", commitment.Id);
}
catch (WebException ex) {
//_logger.Error(String.Format("Email for request commitment ID {0} could not be sent.", commitment.Id), ex);
success = false;
}
Console.WriteLine("Success: {0}. Error Message: {1}", success, errorMessage);
}
示例3: UpdateMessageForProductionGateway
public XmlDocument UpdateMessageForProductionGateway(XmlDocument govTalkMessage)
{
var xd = govTalkMessage.ToXDocument();
var ns = XNamespace.Get("http://www.govtalk.gov.uk/CM/envelope");
if (xd.Element(ns + "GovTalkMessage").Element(ns + "Header").Element(ns + "MessageDetails").Element(ns + "GatewayTimestamp") != null)
xd.Element(ns + "GovTalkMessage").Element(ns + "Header").Element(ns + "MessageDetails").Element(ns + "GatewayTimestamp").Remove();
if (xd.Element(ns + "GovTalkMessage").Element(ns + "Header").Element(ns + "MessageDetails").Element(ns + "GatewayTest") != null)
xd.Element(ns + "GovTalkMessage").Element(ns + "Header").Element(ns + "MessageDetails").Element(ns + "GatewayTest").Remove();
govTalkMessage = xd.ToXmlDocument();
return govTalkMessage;
}
示例4: UpdateMessageForLocalTest
public XmlDocument UpdateMessageForLocalTest(XmlDocument govtalkmessage)
{
#region DontDoThis
// DeSerialize XmlDocument govTalkMessage
// Change properties
// Serialize GovTalkMessage
//GovTalkMessage govTalkMessage = XmlSerializationHelpers.DeserializeMessage(govtalkmessage);
//govTalkMessage.Header.MessageDetails.GatewayTest = "1";
//govTalkMessage.Header.MessageDetails.GatewayTimestampSpecified = true;
//govTalkMessage.Header.MessageDetails.GatewayTimestamp = DateTime.Now;
// OK, so using this method to re-serialize specifically adds the \t whitespace
// Therefore possibly making any previously added IRmark incorrect.
// Avoid deserializing Body here ...
// govtalkmessage = XmlSerializationHelpers.SerializeGovTalkMessage(govTalkMessage);
#endregion DontDoThis
// XmlDocument to XDocument
// Add the elements
// XDocument to XmlDocument
XNamespace GovTalk = "http://www.govtalk.gov.uk/CM/envelope";
XElement GatewayTest = new XElement(GovTalk + "GatewayTest", "1");
XElement GatewayTimestamp = new XElement(GovTalk + "GatewayTimestamp", DateTime.Now);
XmlDocument ModifiedGovTalkMessage = new XmlDocument();
ModifiedGovTalkMessage.PreserveWhitespace = true;
XDocument InProcessXDocument = govtalkmessage.ToXDocument();
InProcessXDocument.Root.Element(GovTalk + "Header").Element(GovTalk + "MessageDetails").Add(GatewayTest);
InProcessXDocument.Root.Element(GovTalk + "Header").Element(GovTalk + "MessageDetails").Add(GatewayTimestamp);
ModifiedGovTalkMessage = InProcessXDocument.ToXmlDocument();
return ModifiedGovTalkMessage;
}
示例5: UpdateMessageForDevGatewayTest
public XmlDocument UpdateMessageForDevGatewayTest(XmlDocument govtalkmessage)
{
XNamespace GovTalk = "http://www.govtalk.gov.uk/CM/envelope";
XElement GatewayTest = new XElement(GovTalk + "GatewayTest", "1");
XmlDocument ModifiedGovTalkMessage = new XmlDocument();
ModifiedGovTalkMessage.PreserveWhitespace = true;
XDocument InProcessXDocument = govtalkmessage.ToXDocument();
if (InProcessXDocument.Root.Element(GovTalk + "Header").Element(GovTalk + "MessageDetails").Element(GovTalk + "GatewayTest") == null)
InProcessXDocument.Root.Element(GovTalk + "Header").Element(GovTalk + "MessageDetails").Add(GatewayTest);
else if (InProcessXDocument.Root.Element(GovTalk + "Header").Element(GovTalk + "MessageDetails").Element(GovTalk + "GatewayTest").Value == "0")
{
InProcessXDocument.Root.Element(GovTalk + "Header").Element(GovTalk + "MessageDetails").Element(GovTalk + "GatewayTest").Remove();
InProcessXDocument.Root.Element(GovTalk + "Header").Element(GovTalk + "MessageDetails").Add(GatewayTest);
}
ModifiedGovTalkMessage = InProcessXDocument.ToXmlDocument();
return ModifiedGovTalkMessage;
}
示例6: TestReadListResponse
static void TestReadListResponse()
{
IConfigurationRepository configurationRepository = new ConfigFileConfigurationRepository();
loggingService = new Log4NetLoggingService(configurationRepository, new ThreadContextService());
LogProviderContext.Current = loggingService;
string filename = @"C:\Temp\LocalDataRequestMessage_2014_10_16_10_33_50.xml";
XmlDocument listResponse = new XmlDocument();
listResponse.Load(filename);
IMessageReader reader = new DefaultMessageReader(loggingService, configurationRepository, listResponse.ToXDocument());
reader.ReadMessage();
string[] results = reader.GetMessageResults<string[]>();
string qualifier = reader.GetQualifier();
string function = reader.GetFunction();
DataTable listResults = reader.GetMessageResults<DataTable>();
GovTalkMessage message = reader.Message();
Console.WriteLine("Message from {0}", message.Header.MessageDetails.ResponseEndPoint.Value.ToString());
}
示例7: DemonstrateReadMessage
/// <summary>
/// Demonstrate using the message reader strategies to get results from a message reply
/// </summary>
/// <param name="loggingService"></param>
/// <param name="messageToRead"></param>
static void DemonstrateReadMessage(ILoggingService loggingService, XmlDocument messageToRead)
{
// Set up a message reading strategy
IMessageReader messageReader = new DefaultMessageReader(loggingService, configurationRepository, messageToRead.ToXDocument());
messageReader.ReadMessage();
// We don't know what we've got back from the Gateway, but all replies are GovTalkMessages
if(messageReader.HasErrors())
{
//There are errors in the results file so we can deal with them
// Get a DataTable of the results and have a look at that
DataTable errorTable = messageReader.GetMessageResults<DataTable>();
// Or set up an error return strategy and do something with that
IErrorReturnCalculator errorCalculator = new DefaultErrorReturnCalculator();
GovTalkMessageGovTalkDetailsError error = messageReader.GetMessageResults<GovTalkMessageGovTalkDetailsError>();
Console.WriteLine(errorCalculator.CalculateErrorReturn(error));
if(error.Number == "3001")
{
ErrorResponse errResponse = messageReader.GetMessageResults<ErrorResponse>();
}
}
else
{
// It's either an acknowledgement so we need to get the poll interval and URL, or a response.
string[] results = messageReader.GetMessageResults<string[]>();
foreach(var result in results)
{
Console.WriteLine(result);
}
if(messageReader.GetQualifier() == "response")
{
string body = messageReader.GetBodyType();
if(body != null)
{
DataTable responseTable = messageReader.GetMessageResults<DataTable>();
LocalHelp.ConsolePrintDataTable(responseTable);
}
else
{
Console.WriteLine("No body content");
}
}
}
GovTalkMessageFileName ReplyNamer = new GovTalkMessageFileName.FileNameBuilder()
.AddLogger(loggingService)
.AddConfigurationRepository(configurationRepository)
.AddMessageIntention("ReplyMessage")
.AddCorrelationId(messageReader.GetCorrelationId())
.AddFilePath(@"C:\Temp\")
.BuildFileName();
string replyFileName = ReplyNamer.ToString();
messageToRead.Save(replyFileName);
}
示例8: TestReadSuccessResponse
public static void TestReadSuccessResponse()
{
IConfigurationRepository configurationRepository = new ConfigFileConfigurationRepository();
ILoggingService loggingService = new Log4NetLoggingService(configurationRepository, new ThreadContextService());
XmlDocument successResponse = new XmlDocument();
successResponse.Load(@"C:\Temp\success_response_78503626913182048.xml");
ReadResponseStrategy reader = new ReadResponseStrategy(loggingService, configurationRepository);
if (reader.IsMatch(successResponse.ToXDocument()))
{
SuccessResponse success = reader.GetBody<SuccessResponse>();
}
}
示例9: ConvertXmlDocumentToXDocument
internal virtual XDocument ConvertXmlDocumentToXDocument(XmlDocument xmlDocument)
{
XDocument xDoc = null;
try
{
xDoc = xmlDocument.ToXDocument();
if (xDoc.Root == null)
{
return null;
}
}
catch (Exception ex)
{
Log.Error(ex);
}
return xDoc;
}
示例10: LoadNode
/// <summary>
/// 根據Xml元素重新加載結點
/// </summary>
/// <param name="desPos">結點坐標</param>
/// <param name="xmlStr">xml字符串</param>
public void LoadNode(Coord desPos, string xmlStr)
{
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.LoadXml(xmlStr);
XElement xmlNode = xmlDocument.ToXDocument().Root;
ElementNode node = ElementNode.GetNode(xmlNode);
CopyNode(node, desPos);
}
示例11: GetTransactions
public IEnumerable<Transacction> GetTransactions(DateTime from, DateTime to)
{
// get settings from config file
// make request to mtrackin's api
// convert request to IEnumerable<Transacction> and return it.
string url = String.Format("http://www.moneytrackin.com/api/rest/listTransactions?project=&startDate={0:yyyy-MM-dd}&endDate={1:yyyy-MM-dd}",
from, to);
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.Method = "GET";
request.Headers.Add("Authorization", String.Format("Basic {0}", ConfigurationManager.AppSettings["ApiAuthorizationKey"]));
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse) {
string xmlResponse;
using (StreamReader reader = new StreamReader(response.GetResponseStream())) {
xmlResponse = reader.ReadToEnd();
xmlResponse = xmlResponse.Replace("result", "transactions");
}
var doc = new XmlDocument();
doc.LoadXml(xmlResponse);
var xdoc = doc.ToXDocument();
var query = from c in xdoc.Descendants("transaction")
select new Transacction {
ID = (long)c.Attribute("id"),
Description = (string)c.Element("description"),
Date = (DateTime)c.Element("date"),
Amount = (decimal)c.Element("amount"),
Tags = c.Descendants("tags").Select(x => x.Element("tag").Value).ToList()
};
return query.ToList();
}
}
示例12: GetErrorContent
/// <summary>
/// Получаем контент сообщения об ошибке
/// </summary>
/// <param name="doc"></param>
/// <returns>Информацию об ошибке</returns>
public VKErrorInfo GetErrorContent(XmlDocument doc)
{
XDocument xDoc = doc.ToXDocument();
if (xDoc != null)
{
VKErrorInfo errors = new VKErrorInfo();
errors.ErrorCode = Convert.ToInt32(xDoc.Element("error").Element("error_code").Value);
errors.ErrorMessage = xDoc.Element("error").Element("error_msg").Value;
errors.ErrorParams = (from item in xDoc.Element("error").Element("request_params").Elements()
where item.Name == "param"
select new VKErrorParams()
{
Key = item.Element("key").Value,
Value = item.Element("value").Value
}).ToList();
return errors;
}
return null;
}
示例13: Main
//.........這裏部分代碼省略.........
new object[]
{
new XElement(name: "name", content: albumNode["name"].InnerText),
new XElement(name: "artist", content: albumNode["artist"].InnerText)
}
}));
}
}
totalAlbums.WriteTo(writer);
}
}
Console.WriteLine(value: "\nalbums.xml created - filtered the albums info");
Console.WriteLine(new string(c: '=', count: 40));
// Iterate through the project dir
var dirPath = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory + "\\..\\..\\");
var projectRoot = new XElement(name: "dir",
content: new object[]
{
new XAttribute(name: "type", value: "root"),
new XAttribute(name: "name", value: dirPath.Name)
});
XElement result = WalkDirectoryTree(dirPath, root);
using (XmlWriter writer = XmlWriter.Create(outputFileName: "../../directories.xml"))
{
result.WriteTo(writer);
}
Console.WriteLine(value: "\ndirectories.xml created - iterated through project dir");
Console.WriteLine(new string(c: '=', count: 40));
// Extract albums prices < 5 years ago
Console.WriteLine(value: "\nAlbums prices < 5 years ago using xPath");
Console.WriteLine(new string(c: '=', count: 40));
XmlNodeList albums = LoadNodesUsingXPath(doc);
int currentYear = DateTime.Now.Year;
foreach (XmlNode node in albums)
{
if (currentYear - int.Parse(node["year"].InnerText) <= 5)
{
Console.WriteLine($"{node["name"].InnerText} - {node["year"].InnerText}");
}
}
Console.WriteLine(value: "\nAlbums prices < 5 years ago using LINQ");
Console.WriteLine(new string(c: '=', count: 40));
(from XmlNode node in doc.DocumentElement.ChildNodes
where currentYear - int.Parse(node["year"].InnerText) <= 5
select node)
.ToList()
.ForEach((n) => Console.WriteLine($"{n["name"].InnerText} - {n["year"].InnerText}"));
// Apply xslt styles
var transformer = new XslCompiledTransform();
transformer.Load(stylesheetUri: "../../catalog.xslt");
transformer.Transform(filename, resultsFile: "../../catalog.html");
Console.WriteLine(value: "\ncatalog.html created - XSLT styles applied");
Console.WriteLine(new string(c: '=', count: 40));
// xsd against xml validation
Console.WriteLine(value: "\nxsd against xml validation");
Console.WriteLine(new string(c: '=', count: 40));
string xsdMarkup = File.ReadAllText(path: "../../catalog.xsd");
var schemas = new XmlSchemaSet();
schemas.Add(targetNamespace: "", schemaDocument: XmlReader.Create(new StringReader(xsdMarkup)));
Console.WriteLine(value: "Validating catalog.xml");
bool error = false;
doc.ToXDocument().Validate(schemas, (o, e) =>
{
Console.WriteLine(format: "{0}", arg0: e.Message);
error = true;
});
Console.WriteLine(error ? "not successful" : "successful");
Console.WriteLine(value: "Validating an empty xml document");
error = false;
new XDocument(
new XElement(name: "Root",
content: new object[]
{
new XElement(name: "Child1", content: "content1"),
new XElement(name: "Child2", content: "content2")
}))
.Validate(schemas, (o, e) =>
{
Console.WriteLine(format: "{0}", arg0: e.Message);
error = true;
});
Console.WriteLine(error ? "not successful" : "successful");
}
示例14: ImportRoute
/// <summary>
/// Reads gpx data from the stream, parses it, and saves to the data store for the specified user.
/// </summary>
/// <param name="inputStream">
/// The input stream.
/// </param>
/// <param name="fileName">
/// The file name.
/// </param>
/// <param name="forceName">
/// If parameter is false, the program will try to extract the name from the uploaded file. Otherwise it will use the value from fileName parameter.
/// </param>
/// <returns>
/// True if the opreation completed successfully. False otherwise.
/// </returns>
public bool ImportRoute(Stream inputStream, string fileName, bool forceName)
{
int result;
var xDocument = new XmlDocument();
using (var xReader = new StreamReader(inputStream))
{
xDocument.Load(xReader);
var newRoute = _xmlParser.ConvertXmlDocumentToRoute(xDocument.ToXDocument(), forceName);
if (forceName)
{
newRoute.Name = fileName;
}
else if (newRoute.Name == null)
{
newRoute.Name = fileName;
}
newRoute.UserId = _userId;
result = _routesRepository.Save(newRoute);
}
return result > -1;
}
示例15: TestDecompressMessage
public static void TestDecompressMessage(XmlDocument compressedXmlDocument)
{
string contents = CommonUtilityHelper.DecompressData(compressedXmlDocument.XmlToBytes());
XmlDocument decompressedDocument = new XmlDocument();
decompressedDocument.LoadXml(contents);
DefaultMessageReader reader = new DefaultMessageReader(loggingService, configurationRepository, decompressedDocument.ToXDocument());
string[] results = reader.GetMessageResults<string[]>();
Console.WriteLine(reader.GetQualifier());
}