Update XML with C# running from command line - c#

Working with: visual studio and C#
I have function to update XML file, while running from the VS it's works and the XML is updated.
While running this function out from the VS for example command line or Jenkins the XML file doesn't update.
My code:
string XMLPath = Path.GetDirectoryName(Path.GetDirectoryName(Path.GetDirectoryName(System.IO.Directory.GetCurrentDirectory())));
public void UpdateXML(string tag, string value)
{
XmlDocument doc = new XmlDocument();
string XMLFile = "";
try{
XMLFile = XMLPath + "\\Test.xml";
doc.Load(XMLFile);
XmlNode node = doc.SelectSingleNode(tag);
node.InnerText = value;
doc.Save(XMLFile);
}
catch (Exception e){}
}
public void Set_ConfigurationXML()
{
UpdateXML("Platform", "web");
}
Any suggestions?

Related

C# append object to xml file using serialization

I am trying append a serialized object to an existing xml file beneath the root element, which I thought would be simple but is proving to be a little challenging.
The problem is in the AddShortcut method but I added some more code for completeness.
I believe what I need to do is:
load the file into an XmlDocument.
navigate to the node I want to append beneath (here the node name is Shortcuts).
create some type of writer and then serialize the object.
save the XmlDocument.
The trouble is in steps 2 and 3. I have tried different variations but I think using XPathNavigator somehow to find the "root" node to append under is a step in the right direction.
I have also looked at almost every question on Stack Overflow on the subject.
Any suggestions welcome. Here is my code
class XmlEngine
{
public string FullPath { get; set; } // the full path to the xmlDocument
private readonly XmlDocument xDoc;
public XmlEngine(string fullPath, string startElement, string[] rElements)
{
FullPath = fullPath;
xDoc = new XmlDocument();
CreateXmlFile(FullPath, startElement, rElements);
}
public void CreateXmlFile(string path, string startElement, string[] rElements)
{
try
{
if (!File.Exists(path))
{
// create a txt writer
XmlTextWriter wtr = new XmlTextWriter(path, System.Text.Encoding.UTF8);
// make sure the file is well formatted
wtr.Formatting = Formatting.Indented;
wtr.WriteProcessingInstruction("xml", "version='1.0' encoding='UTF-8'");
wtr.WriteStartElement(startElement);
wtr.Close();
// write the top level root elements
writeRootElements(path, rElements);
}
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex.Message);
Console.WriteLine("Could not create file: " + path);
}
}
public void AddShortcut(Shortcut s)
{
xDoc.Load(FullPath);
rootNode = xDoc.AppendChild(xDoc.CreateElement("Shortcuts"));
var serializer = new XmlSerializer(s.GetType());
using (var writer = new StreamWriter(FullPath, true))
{
XmlWriterSettings ws = new XmlWriterSettings();
ws.OmitXmlDeclaration = true;
serializer.Serialize(writer, s);
}
xDoc.Save(FullPath);
}
}
This code sample worked for me:
xml:
<?xml version="1.0" encoding="UTF-8"?>
<Launchpad>
<Shortcuts>
<Shortcut Id="1">
<Type>Folder</Type>
<FullPath>C:\SomePath</FullPath>
<Name>SomeFolderName</Name>
</Shortcut>
</Shortcuts>
</Launchpad>
Method:
public void AddShortcut(Shortcut s)
{
xDoc.Load(FullPath);
var rootNode = xDoc.GetElementsByTagName("Shortcuts")[0];
var nav = rootNode.CreateNavigator();
var emptyNamepsaces = new XmlSerializerNamespaces(new[] {
XmlQualifiedName.Empty
});
using (var writer = nav.AppendChild())
{
var serializer = new XmlSerializer(s.GetType());
writer.WriteWhitespace("");
serializer.Serialize(writer, s, emptyNamepsaces);
writer.Close();
}
xDoc.Save(FullPath);
}
load the file into an XmlDocument.
navigate to the node I want to append beneath (here the node name is Shortcuts).
create some type of writer and then serialize the object.
save the XmlDocument
So:
public void AddShortcut(Shortcut s)
{
// 1. load existing xml
xDoc.Load(FullPath);
// 2. create an XML node from object
XmlElement node = SerializeToXmlElement(s);
// 3. append that node to Shortcuts node under XML root
var shortcutsNode = xDoc.CreateElement("Shortcuts")
shortcutsNode.AppendChild(node);
xDoc.DocumentElement.AppendChild(shortcutsNode);
// 4. save changes
xDoc.Save(FullPath);
}
public static XmlElement SerializeToXmlElement(object o)
{
XmlDocument doc = new XmlDocument();
using(XmlWriter writer = doc.CreateNavigator().AppendChild())
{
new XmlSerializer(o.GetType()).Serialize(writer, o);
}
return doc.DocumentElement;
}
This post

Can not read XML document containing ampersand symbol

I am writing a program that reads a XML file with Visual C#. I have a problem reading the Xml file, because it contains invalid XML symbols, for example '&'.
I have to read the XML but I can not modify the document. How can I modify the Xml file using C#? My code so far:
private void button1_Click(object sender, EventArgs e)
{
XmlDocument doc;
doc = new XmlDocument();
doc.Load("nuevo.xml");
XmlNodeList Xpersonas = doc.GetElementsByTagName("personas");
XmlNodeList Xlista = ((XmlElement)Xpersonas[0]).GetElementsByTagName("edad");
foreach (XmlElement nodo in Xlista)
{
string edad = nodo.GetAttribute("edad");
string nombre = nodo.InnerText;
textBox1.Text = nodo.InnerXml;
}
As #EBrown suggested, one possibility would be read the file content in a string variable and replace the & symbol with the correct representation for propert XML & and then parse the XML structure. A possible solution could look like this:
var xmlContent = File.ReadAllText(#"nuevo.xml");
XmlDocument doc;
doc = new XmlDocument();
doc.LoadXml(xmlContent.Replace("&", "&"));
XmlNodeList Xpersonas = doc.GetElementsByTagName("personas");
XmlNodeList Xlista = ((XmlElement)Xpersonas[0]).GetElementsByTagName("edad");
foreach (XmlElement nodo in Xlista)
{
string edad = nodo.GetAttribute("edad");
string nombre = nodo.InnerText;
Console.WriteLine(nodo.InnerXml.Replace("&", "&"));
}
The output is:
34 & 34
If it is ok to use LINQ2XML, then the solution is even shorter, and there is no need to write the reverse(second) replace, because LINQ2XML make this for you automatically:
var xmlContent = File.ReadAllText(#"nuevo.xml");
var xmlDocument = XDocument.Parse(xmlContent.Replace("&", "&"));
var edad = xmlDocument.Root.Element("edad").Value;
Console.WriteLine(edad);
The output is the same as above.

Trying to use a remotely hosted XML file for settings

Apologies for the newbie question, I'm only on day 2 of my adventures with C#...
I'm trying to use a remotely hosted XML file to retrieve some basic settings for my program. I've managed to get it to download and parse the XML file into string variables, but I cannot work out how to make these variables available to the rest of my program.
Here is the code:
public static void getSetting()
{
try
{
XmlDocument xml = new XmlDocument();
xml.Load("http://www.domain.com/s/settings.xml");
XmlNodeList xnList = xml.SelectNodes("/Settings/Setting");
string strEnabled = ""; string strPort = "";
string strPac = ""; string strRules = ""; string strUpdateUrl = "";
foreach (XmlNode xn in xnList)
{
strEnabled = xn["Enabled"].InnerText;
strPort = xn["Port"].InnerText;
strPac = xn["Pac"].InnerText;
strRules = xn["Rules"].InnerText;
strUpdateUrl = xn["UpdateUrl"].InnerText;
}
}
catch (Exception e)
{
Console.WriteLine("Unable to download settings: " + e);
}
}
public static void useSettings()
{
//use the settings in here
}
I'd also appreciate any critique on my code as I'm still getting to grips with everything and realise that I'm probably not going about this the best way.

C# crashes on save (doc.Save(PATH);)

This program crashes on debug and highlights the "doc.Save(PATH);" at the end of the code.
I am trying to save the variables cookieScore, additionAddition, and additionMultiplier into an XML file.
I am getting information about it from here "http://visualcsharptutorials.com/net-framework/writing-xml-file"
private XmlDocument doc;
string PATH = #"C:\sample.xml";
private void saveBtn_Click(object sender, EventArgs e)
{
doc = new XmlDocument();
if (!System.IO.File.Exists(PATH))
{
XmlDeclaration declaration = doc.CreateXmlDeclaration("1.0", "UTF-8", "yes");
XmlComment comment = doc.CreateComment("This is saved game data");
XmlElement root = doc.CreateElement("data");
XmlElement data = doc.CreateElement("data");
XmlAttribute addition = doc.CreateAttribute("addition");
XmlElement additionNumber = doc.CreateElement("additionNumber");
XmlElement multiplicationNumber = doc.CreateElement("multiplicationNumber");
XmlElement cookieSave = doc.CreateElement("cookieSave");
addition.Value = "addition";
additionNumber.InnerText = additionAddition.ToString();
multiplicationNumber.InnerText = additionMultiplier.ToString();
cookieSave.InnerText = cookieScore.ToString();
doc.AppendChild(declaration);
doc.AppendChild(comment);
doc.AppendChild(root);
root.AppendChild(data);
data.Attributes.Append(addition);
data.AppendChild(cookieSave);
data.AppendChild(additionNumber);
data.AppendChild(multiplicationNumber);
doc.Save(PATH);
}
else
{
}
My guess is you're getting an access related exception because you're trying to write to the root of your C drive. Try writing to your desktop instead:
string PATH = #"C:\Users\[yourusername]\Desktop\sample.xml";
Another option would be to try to run your EXE as admin. If it works, then you know that's your problem.

c# winforms Form Load ComboBox DropDownList get value from XML file

XML File:
<?xml version="1.0" encoding="utf-16"?>
<XMLFILE>
<Active>0</Active>
<Hits_Method>1</Hits_Method>
</XMLFILE>
What i'm trying to do is on Form1_Load get the value of ComboBox4 from XML File (Hits_Method) and when the program start to show me the value. i try something like this but didn't work out
// ------------------- StartUP Load
private void Form1_Load(object sender, EventArgs e)
{
// --------------- Read XML File / Data: Settings_Ads_General
String xmlfile = "Settings_General.xml";
XmlTextReader xreader = new XmlTextReader(xmlfile);
string comboBox4Value = xreader.GetAttribute("Hits_Method");
comboBox4.SelectedIndex = comboBox4Value;
}
Try this instead:
private void Form1_Load(object sender, EventArgs e)
{
// --------------- Read XML File / Data: Settings_Ads_General
String xmlfile = "Settings_General.xml";
XmlDocument doc = new XmlDocument();
doc.Load(xmlfile);
string comboBox4Value = doc.SelectSingleNode("XMLFILE/Hits_Method").InnerText;
comboBox4.SelectedIndex = Convert.ToInt32(comboBox4Value);
}
The SelectSingleNode method extracts data based on an XPath expression. And "XMLFILE/Hits_Method" is the XPath that leads to your value.
I will use XmlDocument and XmlNode classes.
{
String sPath = "file.xml"
XmlDocument doc = new XmlDocument();
doc.Load(sPath)
XmlNode node = doc.SelectSingleNode("XMLFILE/Hits_Method");
if (node != null)
comboBox4.SelectedIndex = node.InnerText;
}

Categories