本文整理匯總了C#中System.Xml.XmlDocument.Load方法的典型用法代碼示例。如果您正苦於以下問題:C# XmlDocument.Load方法的具體用法?C# XmlDocument.Load怎麽用?C# XmlDocument.Load使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類System.Xml.XmlDocument
的用法示例。
在下文中一共展示了XmlDocument.Load方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的C#代碼示例。
示例1: LoadXmlFile
/// <summary>
/// 加載XML文件
/// </summary>
/// <param name="xmlDoc">XML文件</param>
/// <param name="strXmlPath">XML文件的路徑</param>
/// <param name="strRoot">根節點的值</param>
public static void LoadXmlFile(XmlDocument xmlDoc, string strXmlPath, string strRoot)
{
if (strXmlPath == string.Empty)
{
return;
}
if (xmlDoc == null)
{
return;
}
if (System.IO.File.Exists(strXmlPath))
{
xmlDoc.Load(strXmlPath);
}
else
{
XmlNode xmlNode = xmlDoc.CreateXmlDeclaration("1.0", "utf-8", null);
xmlDoc.AppendChild(xmlNode);
XmlElement xmlElement = xmlDoc.CreateElement("", "Root", "");
XmlText xmlText = xmlDoc.CreateTextNode(strRoot);
xmlElement.AppendChild(xmlText);
xmlDoc.AppendChild(xmlElement);
try
{
xmlDoc.Save(strXmlPath);
xmlDoc.Load(strXmlPath);
}
catch (System.Exception e)
{
return;
}
}
}
示例2: XmlDocument
/// <summary>
///
/// </summary>
/// <param name="optionsRoot">The options root object</param>
/// <param name="context">The file name for XML Document</param>
void IVisitorWithContext.Visit(UIOptionRootType optionsRoot, object context)
{
XmlDocument xmlDoc = new XmlDocument();
Stream stream = context as Stream;
if (stream == null)
{
xmlDoc.Load((string) context);
}
else
{
xmlDoc.Load(stream);
}
XmlNamespaceManager nsmgr = new XmlNamespaceManager(xmlDoc.NameTable);
nsmgr.AddNamespace("ws", "http://schemas.workshare.com/Workshare.OptionMap.xsd");
string xpath = "ws:OptionMap/ws:Category";
XmlNodeList categories = xmlDoc.SelectNodes(xpath, nsmgr);
foreach (XmlNode node in categories)
{
UIOptionCategoryType category = new UIOptionCategoryType();
optionsRoot.Categories.Add(category);
category.Accept(this, node);
}
}
示例3: LoadXML
public static XmlDocument LoadXML(string URL, string xmlFileName)
{
XmlDocument xml = new XmlDocument();
string dire = Directory.GetCurrentDirectory();
string xmlFile = dire + "\\XML\\" + xmlFileName;
if (File.Exists(xmlFile))
{
FileStream stream = new FileStream(xmlFile, FileMode.Open);
xml.Load(stream);
stream.Close();
}
else
{
try
{
xml.Load(URL);
}
catch (System.Exception)
{
Console.WriteLine("Date Feed Not Found.");
xml = null;
return xml;
}
Console.WriteLine("Date Feed Updated.");
FileStream stream = new FileStream(xmlFile, FileMode.Create);
xml.Save(stream);
stream.Close();
}
return xml;
}
示例4: _openBtn_Click
private void _openBtn_Click(object sender, RoutedEventArgs e)
{
try
{
XmlDocument doc = new XmlDocument();
if (_urlBtn.IsChecked==true)
{
doc.Load(_inputTbx.Text);
}
if (_streamBtn.IsChecked==true)
{
FileStream stream = new FileStream(_inputTbx.Text, FileMode.Open);
doc.Load(stream);
stream.Close();
}
if (_stringBtn.IsChecked == true)
{
doc.LoadXml(_inputTbx.Text);
}
MessageBox.Show(doc.DocumentElement.Name);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
示例5: RecordAgent
public void RecordAgent()
{
#region CLIENT RECORD
if (!File.Exists(Generate.xmlPath))
return;
XmlDocument xmld = new XmlDocument();
try { xmld.Load(Generate.xmlPath); }
catch { Thread.Sleep(50); xmld.Load(Generate.xmlPath); }
foreach (XmlElement xmle in xmld.GetElementsByTagName("clients"))
{
Coming c = new Coming();
c.id = xmle["id"].InnerText;
c.lep = xmle["lep"].InnerText;
c.macAddress = xmle["macAddress"].InnerText;
c.licence = xmle["licence"].InnerText;
c.Session = Convert.ToInt32(xmle["Session"].InnerText);
c.port = Convert.ToInt32(xmle["port"].InnerText);
c.Address = xmle["Address"].InnerText;
c.cep = new IPEndPoint(IPAddress.Parse(c.Address), c.port);
Agent.clients.Add(c.id, c);
}
try { xmld.Save(Generate.xmlPath); }
catch { Thread.Sleep(50); xmld.Save(Generate.xmlPath); }
Generate.isFirst = false;
("SERVER WORKING FIRST TIME & TRANSFERRED XML DATA TO Agent.clients").p2pDEBUG();
#endregion
}
示例6: Battle
public Battle(SPRWorld sprWorld, int botHalfWidth, World world, int currentLevel)
{
this.sprWorld = sprWorld;
this.botHalfWidth = botHalfWidth;
this.world = world;
xmlDoc = new XmlDocument();
if (nextAllies == "")
{
xmlDoc.Load("Games/SuperPowerRobots/Storage/Allies.xml");
}
else
{
xmlDoc.LoadXml(nextAllies);
}
//xmlDoc.
XmlNodeList nodes = xmlDoc.GetElementsByTagName("Bot");
Vector2[] edges = { new Vector2(-botHalfWidth, -botHalfWidth) * Settings.MetersPerPixel, new Vector2(botHalfWidth, -botHalfWidth) * Settings.MetersPerPixel, new Vector2(botHalfWidth, botHalfWidth) * Settings.MetersPerPixel, new Vector2(-botHalfWidth, botHalfWidth) * Settings.MetersPerPixel };
CreateBots(nodes, edges);
xmlDoc.Load("Games/SuperPowerRobots/Storage/Battles.xml");
nodes = xmlDoc.GetElementsByTagName("Level");
nodes = nodes[currentLevel].ChildNodes;
CreateBots(nodes, edges);
}
示例7: Upgrades0210
// Accumulation format is now called Victory.
private static void Upgrades0210()
{
var xml = new XmlDocument();
if (Config.Settings.SeparateEventFiles)
{
var targetPath = Path.Combine(Program.BasePath, "Tournaments");
if (!Directory.Exists(targetPath)) Directory.CreateDirectory(targetPath);
var files = new List<string>(Directory.GetFiles(targetPath, "*.tournament.dat",
SearchOption.TopDirectoryOnly));
files.AddRange(Directory.GetFiles(targetPath, "*.league.dat",
SearchOption.TopDirectoryOnly));
foreach (string filename in files)
{
xml.Load(filename);
var oldNodes = xml.SelectNodes("//Events/Tournaments/Tournament/Format[. = 'Accumulation']");
if (oldNodes != null)
foreach (XmlNode oldNode in oldNodes)
oldNode.InnerText = "Victory";
oldNodes = xml.SelectNodes("//Events/Leagues/League/Format[. = 'Accumulation']");
if (oldNodes != null)
foreach (XmlNode oldNode in oldNodes)
oldNode.InnerText = "Victory";
var writer = new XmlTextWriter(new FileStream(filename, FileMode.Create), null)
{
Formatting = Formatting.Indented,
Indentation = 1,
IndentChar = '\t'
};
xml.WriteTo(writer);
writer.Flush();
writer.Close();
}
}
else if (File.Exists(Path.Combine(Program.BasePath, "Events.dat")))
{
xml.Load(Path.Combine(Program.BasePath, "Events.dat"));
var oldNodes = xml.SelectNodes("//Events/Tournaments/Tournament/Format[. = 'Accumulation']");
if (oldNodes != null)
foreach (XmlNode oldNode in oldNodes)
oldNode.InnerText = "Victory";
oldNodes = xml.SelectNodes("//Events/Leagues/League/Format[. = 'Accumulation']");
if (oldNodes != null)
foreach (XmlNode oldNode in oldNodes)
oldNode.InnerText = "Victory";
var writer = new XmlTextWriter(new FileStream(Path.Combine(Program.BasePath,
"Events.dat"), FileMode.Create), null)
{
Formatting = Formatting.Indented,
Indentation = 1,
IndentChar = '\t'
};
xml.WriteTo(writer);
writer.Flush();
writer.Close();
}
}
示例8: Workspace
public Workspace(string workspacepath)
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(workspacepath); //加載XML文檔
XmlNode Node = xmlDoc.SelectSingleNode("workspace");
XmlNode IDNode = Node.FirstChild ;
XmlNode NameNode = Node.LastChild;
if (IDNode != null)
{
ID = IDNode.InnerText;
}
if (NameNode != null)
{
Name = NameNode.InnerText;
}
string namespacepath = workspacepath.Replace("workspace.xml", "namespace.xml");
xmlDoc.Load(namespacepath);
Node = xmlDoc.SelectSingleNode("namespace");
XmlNode PrefixNode = Node.ChildNodes[1];
XmlNode UriNode = Node.ChildNodes[2];
if (PrefixNode != null)
{
this.Prefix = PrefixNode.InnerText;
this.URI = UriNode.InnerText;
}
}
示例9: GetXMLDocument
public XmlDocument GetXMLDocument(string path)
{
XmlDocument xmlDocument = new XmlDocument();
try
{
if (path.StartsWith("http"))
{
HttpWebRequest request = new HTTPConnector().BuildWebRequest(path, "text/xml");
using (WebResponse response = request.GetResponse())
{
Stream xmlStream = response.GetResponseStream();
xmlDocument.Load(xmlStream);
xmlStream.Close();
response.Close();
}
}
else
{
xmlDocument.Load(path);
}
}
catch (Exception exception)
{
ErrorService.Log("XMLConnector", "GetXMLDocument", path, exception);
}
return xmlDocument;
}
示例10: XmlWriter
public XmlWriter()
{
string filename = AppDomain.CurrentDomain.BaseDirectory.ToString() + @"/Table1.xml";
XmlDocument xmlDoc = new XmlDocument();
try
{
xmlDoc.Load(filename);
}
catch (System.IO.FileNotFoundException ex)
{
Console.WriteLine(ex);
XmlTextWriter xmlWriter = new XmlTextWriter(filename, System.Text.Encoding.UTF8);
xmlWriter.Formatting = Formatting.Indented;
xmlWriter.WriteProcessingInstruction("xml", "version='1.0' encoding='UTF-8'");
xmlWriter.WriteStartElement("Table");
xmlWriter.WriteStartElement("Players");
xmlWriter.WriteEndElement();
xmlWriter.WriteStartElement("Dealer");
xmlWriter.WriteStartElement("DealerCards");
xmlWriter.WriteEndElement();
xmlWriter.WriteEndElement();
xmlWriter.Close();
xmlDoc.Load(filename);
}
}
示例11: getCompList
public static string getCompList(bool test)
{
string sources="";
try
{
XmlDocument doc = new XmlDocument();
if (test)
{
doc.Load(AppEnvironment.strListFileTest);
}
else
{
doc.Load(AppEnvironment.strListFile);
}
sources = doc.DocumentElement["others"].ChildNodes[1].InnerText;
}
catch ( System.IO.IOException e )
{
//saveConfigXML();
sources = AppEnvironment.strDefaultPath;
Console.Out.WriteLine ( "Error: " + e.Message );
}
return sources;
}
示例12: GetInfo
void GetInfo()
{
// создаем xml-документ
XmlDocument xmlDocument = new XmlDocument ();
// делаем запрос на получение имени пользователя
WebRequest webRequest = WebRequest.Create ("https://api.vk.com/method/users.get.xml?&access_token=" + token);
WebResponse webResponse = webRequest.GetResponse ();
Stream stream = webResponse.GetResponseStream ();
xmlDocument.Load (stream);
string name = xmlDocument.SelectSingleNode ("response/user/first_name").InnerText;
// делаем запрос на проверку,
webRequest = WebRequest.Create ("https://api.vk.com/method/groups.isMember.xml?group_id=20629724&access_token=" + token);
webResponse = webRequest.GetResponse ();
stream = webResponse.GetResponseStream ();
xmlDocument.Load (stream);
bool habrvk = (xmlDocument.SelectSingleNode ("response").InnerText =="1");
// выводим диалоговое окно
var builder = new AlertDialog.Builder (this);
// пользователь состоит в группе "хабрахабр"?
if (!habrvk) {
builder.SetMessage ("Привет, "+name+"!\r\n\r\nТы не состоишь в группе habrahabr.Не хочешь вступить?");
builder.SetPositiveButton ("Да", (o, e) => {
// уточнив, что пользователь желает вступить, отправим запрос
webRequest = WebRequest.Create ("https://api.vk.com/method/groups.join.xml?group_id=20629724&access_token=" + token);
webResponse = webRequest.GetResponse ();
});
builder.SetNegativeButton ("Нет", (o, e) => {
});
} else {
builder.SetMessage ("Привет, "+name+"!\r\n\r\nОтлично! Ты состоишь в группе habrahabr.");
builder.SetPositiveButton ("Ок", (o, e) => {
});
}
builder.Create().Show();
}
示例13: Main
static void Main()
{
XmlDocument doc = new XmlDocument();
doc.Load("../../../catalogue.xml");
XmlNode catalogue = doc.DocumentElement;
foreach (XmlNode album in catalogue.SelectNodes("album"))
{
int albumPrice = int.Parse(album["price"].InnerText);
if (albumPrice > 20)
{
catalogue.RemoveChild(album);
}
}
doc.Save("../../../catalogueReduced.xml");
doc.Load("../../../catalogueReduced.xml");
XmlNode updated = doc.DocumentElement;
foreach (XmlNode album in updated.ChildNodes)
{
Console.WriteLine("album: {0} price: {1} ", album["name"].InnerText, album["price"].InnerText);
}
}
示例14: GetXmlDocument
private static XmlDocument GetXmlDocument(string path)
{
using (Stream s = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.Read))
{
byte[] buffer = new byte[2];
s.Read(buffer, 0, 2);
s.Position = 0;
XmlDocument document = new XmlDocument();
XmlReaderSettings xrSettings = new XmlReaderSettings();
xrSettings.DtdProcessing = DtdProcessing.Ignore;
// if first two bytes are "MZ" then we're looking at an .exe or a .dll not a .manifest
if ((buffer[0] == 0x4D) && (buffer[1] == 0x5A))
{
Stream m = EmbeddedManifestReader.Read(path);
if (m == null)
throw new BadImageFormatException(null, path);
using (XmlReader xr = XmlReader.Create(m, xrSettings))
{
document.Load(xr);
}
}
else
{
using (XmlReader xr = XmlReader.Create(s, xrSettings))
{
document.Load(xr);
}
}
return document;
}
}
示例15: writeOptions
public void writeOptions()
{
Directory.CreateDirectory(OPTIONS_PATH);
XmlDocument xmlDoc = new XmlDocument();
try
{
xmlDoc.Load(OPTIONS_FILE);
}
catch (System.IO.FileNotFoundException)
{
//if file is not found, create a new xml file
XmlTextWriter xmlWriter = new XmlTextWriter(OPTIONS_FILE, System.Text.Encoding.UTF8);
xmlWriter.Formatting = Formatting.Indented;
xmlWriter.WriteProcessingInstruction("xml", "version='1.0' encoding='UTF-8'");
xmlWriter.WriteStartElement("root");
//If WriteProcessingInstruction is used as above,
//Do not use WriteEndElement() here
//xmlWriter.WriteEndElement();
//it will cause the <Root> to be <Root />
xmlWriter.Close();
xmlDoc.Load(OPTIONS_FILE);
}
XmlNode root = xmlDoc.DocumentElement;
root.AppendChild(asXML(root));
xmlDoc.Save(OPTIONS_FILE);
}