I've got a Web Service that uses an XML document and I'm trying to add a function that adds a new node to the XML document. It runs fine and doesn't break, but the save function doesn't seem to work? Here's the code;
[WebMethod]
public void AddNodeTEST()
{
XmlDocument xmlUpdateCfg = new XmlDocument();
try
{
xmlUpdateCfg.Load(Context.Request.MapPath("Updates.xml"));
}
catch (Exception ex)
{
}
XmlNode updateInfo = xmlUpdateCfg.SelectSingleNode("updateinfo");
/* Create the downloadmodule node */
XmlNode newDownloadModule = xmlUpdateCfg.CreateNode(XmlNodeType.Element, "downloadmodule", null);
newDownloadModule.InnerText = "download/test.CAB";
XmlAttribute downloadModuleName = xmlUpdateCfg.CreateAttribute("name");
downloadModuleName.Value = "Test";
newDownloadModule.Attributes.Append(downloadModuleName);
/* Create the version node */
XmlNode newVersion = xmlUpdateCfg.CreateNode(XmlNodeType.Element, "version", null);
XmlAttribute versionMaj = xmlUpdateCfg.CreateAttribute("maj");
versionMaj.Value = "1";
XmlAttribute versionMin = xmlUpdateCfg.CreateAttribute("min");
versionMin.Value = "2";
XmlAttribute versionBld = xmlUpdateCfg.CreateAttribute("bld");
versionBld.Value = "3";
XmlAttribute versionRev = xmlUpdateCfg.CreateAttribute("rev");
versionRev.Value = "4";
newVersion.Attributes.Append(versionMaj);
newVersion.Attributes.Append(versionMin);
newVersion.Attributes.Append(versionBld);
newVersion.Attributes.Append(versionRev);
/* Add the newVersion node to the newDownloadModule node */
newDownloadModule.AppendChild(newVersion);
/* Add the newDownloadModule to the updateinfo Node*/
updateInfo.AppendChild(newDownloadModule);
xmlUpdateCfg.Save("Updates.xml");
}
and here is the XML structure;
<?xml version="1.0" encoding="utf-8" ?>
<updateinfo>
<downloadmodule name="test">
<version maj="1" min="0" bld="4" rev="0"/>
Download/cabfile.CAB
</downloadmodule>
</updateinfo>
Any help is appreciated, thanks!.
Shouldn't you be calling xmlUpdateCfg.Save(Context.Request.MapPath("Updates.xml")) so that it saves it to the same location it read it from?
Related
I have code for changing connection string in app.config. But when i change the database i encounter an error because the linq to sql.dbml is not updated to the database i changed. I need to close the program and open again to take effect the changes. What should i do to update my linq to sql.dbml?
var name = "DbName";
bool isNew = false;
string path = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile;
XmlDocument doc = new XmlDocument();
doc.Load(path);
XmlNodeList list = doc.DocumentElement.SelectNodes(string.Format("connectionStrings/add[#name='{0}']", name));
XmlNode node;
isNew = list.Count == 0;
if (isNew)
{
node = doc.CreateNode(XmlNodeType.Element, "add", null);
XmlAttribute attribute = doc.CreateAttribute("name");
attribute.Value = name;
node.Attributes.Append(attribute);
attribute = doc.CreateAttribute("connectionString");
attribute.Value = "";
node.Attributes.Append(attribute);
attribute = doc.CreateAttribute("providerName");
attribute.Value = "System.Data.SqlClient";
node.Attributes.Append(attribute);
}
else
{
node = list[0];
}
string conString = node.Attributes["connectionString"].Value;
SqlConnectionStringBuilder conStringBuilder = new SqlConnectionStringBuilder(conString);
conStringBuilder.DataSource = txtConnectServername.Text;
conStringBuilder.InitialCatalog = "AlTayerDB";
conStringBuilder.PersistSecurityInfo = true;
conStringBuilder.UserID = txtConnectUserId.Text;
conStringBuilder.Password = txtConnectAdapterPassword.Text;
conStringBuilder.MultipleActiveResultSets = true;
node.Attributes["connectionString"].Value = conStringBuilder.ConnectionString;
if (isNew)
{
doc.DocumentElement.SelectNodes("connectionStrings")[0].AppendChild(node);
}
doc.Save(path);
I suggest you to follow this - How do I (update/insert/remove) the config file during runtime? for complete information about this topic:
Modify existing values in the config file during runtime.
Because the Configuration.AppSettings property is read-only, in order to modify the current application settings value, we must use the XmlDocument class to directly update the application configuration file as an XML document.
Here is the original App.config file:
<configuration>
<appSettings>
<add key="Setting1" value="1" />
<add key="Setting2" value="2" />
</appSettings>
</configuration>
Here is the code sample to modify the application settings value:
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
foreach (XmlElement element in xmlDoc.DocumentElement)
{
if (element.Name.Equals("appSettings"))
{
foreach (XmlNode node in element.ChildNodes)
{
if (node.Attributes[0].Value.Equals("Setting1"))
{
node.Attributes[1].Value = "New Value";
}
}
}
}
xmlDoc.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
ConfigurationManager.RefreshSection("appSettings");
If this does not suite to requirement then check the below references:
Change the value in app.config file dynamically
App.Config change value
update app.config file programatically with ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
Hi I have an xml data returned from another service. It looks like this
<?xml version="1.0" encoding="UTF-8"?>
<response xmlns="http://test.com/group/application" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Response>
<Response>
<ReturnCode>0</ReturnCode>
<Message>Sucess</Message>
<Data>PRINT 'This is a test #2'</Data>
</Response>
</Response>
</response>
I need the value of Data, Message and ReturnCode. The value inside the Data(PRINT 'This is a test #2') node could be single line or thousands of lines..
I am using this C# code to get the values
XmlDocument xm = new XmlDocument();
string Response = obj.getContent(str, 1, 73810, SHA);
//Console.WriteLine("Response" + Response);
xm.LoadXml(Response);
Console.WriteLine(xm.InnerXml);
XmlNode oldCd;
XmlElement root = xm.DocumentElement;
Console.WriteLine(root.InnerText);
oldCd = root.SelectSingleNode("/response/Response/Response/ReturnCode/Message/Data/");
static void Main()
{
try
{
svc obj = new svc();
..
//XmlDocument xm = new XmlDocument();
string rsp = obj.getContent(..;
String myEncodedString;
myEncodedString = obj.XmlDecode(rsp);
XNamespace xmlns = XNamespace.Get("http://xxxx.com/xxx/xx");
XDocument doc = XDocument.Parse(myEncodedString);
Console.WriteLine(obj.Return_Message_Data("ReturnCode", myEncodedString));
Console.WriteLine(obj.Return_Message_Data("Message", myEncodedString));
Console.WriteLine(obj.Return_Message_Data("Data", myEncodedString));
Console.ReadLine();
}
catch (Exception e)
{
Console.WriteLine(e);
Console.ReadLine();
}
}
Try this
XmlDocument xml = new XmlDocument();
xml.LoadXml(myXmlString); //myXmlString is the xml file in string //copying xml to string: string myXmlString = xmldoc.OuterXml.ToString();
XmlNodeList xnList = xml.SelectNodes("/responset[#*]/Response");
foreach (XmlNode xn in xnList)
{
XmlNode response = xn.SelectSingleNode("Response");
if (response != null)
{
string rc = response["ReturnCode"].InnerText;
string msg = example["Message"].InnerText;
string data = example["Data"].InnerText;
}
}
I want to read specific data from an XML file.
This is what I have come up with so far:
When I run my program without the (if (reader.Name == ControlID)) line reader.Value returns the right value,but when I include the if clause,it returns null
public void GetValue(string ControlID)
{
XmlTextReader reader = new System.Xml.XmlTextReader("D:\\k.xml");
string contents = "";
while (reader.Read())
{
reader.MoveToContent();
if (reader.Name == ControlID)
contents = reader.Value;
}
}
Go through following code:
XmlDocument doc = new XmlDocument();
doc.Load(filename);
string xpath = "/Path/.../config"
foreach (XmlElement elm in doc.SelectNodes(xpath))
{
Console.WriteLine(elm.GetAttribute("id"), elm.GetAttribute("desc"));
}
Using XPathDocument (faster, smaller memory footprint, read-only, weird API):
XPathDocument doc = new XPathDocument(filename);
string xpath = "/PathMasks/Mask[#desc='Mask_X1']/config"
XPathNodeIterator iter = doc.CreateNavigator().Select(xpath);
while (iter.MoveNext())
{
Console.WriteLine(iter.Current.GetAttribute("id"), iter.Current.GetAttribute("desc'));
}
Can also refer this link:
http://support.microsoft.com/kb/307548
This might be helpful to you.
You can try the following code for example xPath query:
XmlDocument doc = new XmlDocument();
doc.Load("k.xml");
XmlNode absoluteNode;
/*
*<?xml version="1.0" encoding="UTF-8"?>
<ParentNode>
<InfoNode>
<ChildNodeProperty>0</ChildNodeProperty>
<ChildNodeProperty>Zero</ChildNodeProperty>
</InfoNode>
<InfoNode>
<ChildNodeProperty>1</ChildNodeProperty>
<ChildNodeProperty>One</ChildNodeProperty>
</InfoNode>
</ParentNode>
*/
int parser = 0
string nodeQuery = "//InfoNode//ChildNodeProperty[text()=" + parser + "]";
absoluteNode = doc.DocumentElement.SelectSingleNode(nodeQuery).ParentNode;
//return value is "Zero" as string
var nodeValue = absoluteNode.ChildNodes[1].InnerText;
code below:
protected void generate_Click(object sender, EventArgs e)
{
XmlDocument doc = new XmlDocument();
doc.PreserveWhitespace = true;
doc.Load("XmlFileName");
XmlNode node = doc.SelectSingleNode("ChartData/XaxisFields/XaxisField");
if (node != null)
{
node.ChildNodes.Item(0).InnerXml = "hi";
doc.Save("XmlFileName");
}
}
Showing null refernce here,
node.ChildNodes.Item(0).InnerXml = "hi";
Is the code is correct,the code behind running not showing any error
but the Xaxisfield is not added.
<?xml version="1.0" encoding="utf-8" ?>
<ChartData>
<XaxisFields>
<XaxisField></XaxisField>
</XaxisFields>
</ChartData>
List item
I want to add the childnode Xaxisfield in the xml file by selcting the particular parent node
You can use Linq to Xml to select your node and update its value:
var xdoc = XDocument.Load("XmlFileName");
xdoc.Root.Element("XaxisFields").Element("XaxisField").Value = "hi";
// OR
// xdoc.XPathSelectElement("//XaxisField").Value = "hi";
xdoc.Save("XmlFileName");
Also your code is not working because there is no child nodes of XaxisField node. This will work:
XmlDocument doc = new XmlDocument();
doc.PreserveWhitespace = true;
doc.Load("XmlFileName");
XmlNode node = doc.SelectSingleNode("ChartData/XaxisFields/XaxisField");
if (node != null)
{
node.InnerXml = "hi";
doc.Save("XmlFileName");
}
Hey all i have code to write to an xml doc from asp
string filePath = Server.MapPath("../XML/MyXmlDoc.xml");
XmlDocument xmlDoc = new XmlDocument();
try
{
xmlDoc.Load(filePath);
}
catch (System.IO.FileNotFoundException)
{
//if file is not found, create a new xml file
XmlTextWriter xmlWriter = new XmlTextWriter(filePath, System.Text.Encoding.UTF8);
xmlWriter.Formatting = Formatting.Indented;
xmlWriter.WriteProcessingInstruction("xml", "version='1.0' encoding='UTF-8'");
string startElement = "markings";
xmlWriter.WriteStartElement(startElement);
xmlWriter.Close();
xmlDoc.Load(filePath);
}
XmlNode root = xmlDoc.DocumentElement;
XmlElement mainNode = xmlDoc.CreateElement("mark");
XmlElement childNode1 = xmlDoc.CreateElement("studentFirstName");
XmlElement childNode2 = xmlDoc.CreateElement("studentLastName");
XmlElement childNode3 = xmlDoc.CreateElement("className");
XmlElement childNode4 = xmlDoc.CreateElement("marks");
XmlText childTextNode1 = xmlDoc.CreateTextNode("");
XmlText childTextNode2 = xmlDoc.CreateTextNode("");
XmlText childTextNode3 = xmlDoc.CreateTextNode("");
XmlText childTextNode4 = xmlDoc.CreateTextNode("");
root.AppendChild(mainNode);
//this portion can be added to a foreach loop if you need to add multiple records
childTextNode1.Value = "John";
childTextNode2.Value = "Doe";
childTextNode3.Value = "Biology";
childTextNode4.Value = "99%";
mainNode.AppendChild(childNode1);
childNode1.AppendChild(childTextNode1);
mainNode.AppendChild(childNode2);
childNode2.AppendChild(childTextNode2);
mainNode.AppendChild(childNode3);
childNode3.AppendChild(childTextNode3);
mainNode.AppendChild(childNode4);
childNode4.AppendChild(childTextNode4);
//end of loop section
xmlDoc.Save(filePath);
which works fine but i want to store the xml in the following structure
graph
set name="John Doe" value="99";
/graph
instead of
name John Doe /name
value 99 /value
is there a way to store the xml like this? thanks all
You can add an attribute to your XmlElement by using the following syntax (C#) :
XmlAttribute value = xmlDoc.CreateAttribute("value");
childNode1.attributes.appendChild(value);
Hope this helps !
This code will do what you're looking for:
XmlElement graph = xmlDoc.CreateElement("graph");
XmlAttribute name = xmlDoc.CreateAttribute("name");
name.Value = "John Doe";
XmlAttribute value = xmlDoc.CreateAttribute("value");
value.Value = "99";
graph.SetAttributeNode(name);
graph.SetAttributeNode(value);
mainNode.AppendChild(graph);