How to modify existing XML file with XmlDocument and XmlNode in C#
You need to do something like this:
// instantiate XmlDocument and load XML from file
XmlDocument doc = new XmlDocument();
doc.Load(@"D:\test.xml");
// get a list of nodes - in this case, I'm selecting all <AID> nodes under
// the <GroupAIDs> node - change to suit your needs
XmlNodeList aNodes = doc.SelectNodes("/Equipment/DataCollections/GroupAIDs/AID");
// loop through all AID nodes
foreach (XmlNode aNode in aNodes)
{
// grab the "id" attribute
XmlAttribute idAttribute = aNode.Attributes["id"];
// check if that attribute even exists...
if (idAttribute != null)
{
// if yes - read its current value
string currentValue = idAttribute.Value;
// here, you can now decide what to do - for demo purposes,
// I just set the ID value to a fixed value if it was empty before
if (string.IsNullOrEmpty(currentValue))
{
idAttribute.Value = "515";
}
}
}
// save the XmlDocument back to disk
doc.Save(@"D:\test2.xml");
Modify xml with Xmldocument in C#
XmlNodeList aNodes returns null because the xml contains these namespace declarations:
<InvoicesDoc xmlns=\"http://www.aade.gr/myDATA/invoice/v1.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"
xsi:schemaLocation=\"http://www.aade.gr/myDATA/invoice/v1.0/InvoicesDoc-v0.6.xsd\"
xmlns:icls=\"https://www.aade.gr/myDATA/incomeClassificaton/v1.0\"
xmlns:ecls=\"https://www.aade.gr/myDATA/expensesClassificaton/v1.0\">
You need to manage your xml doing something like this:
XmlDocument xml = new XmlDocument();
xml.Load(@"https://www.aade.gr/sites/default/files/2020-09/SampleXML_1.1%20%20%28%CE%A4%CE%99%CE%9C-%CE%A0%CE%A9%CE%9B%CE%97%CE%A3%CE%97%CE%A3_%CE%91%CE%A5%CE%A4%CE%9F%CE%A4%CE%99%CE%9C%29%20.xml");
XmlNamespaceManager manager = new XmlNamespaceManager(xml.NameTable);
manager.AddNamespace("InvoicesDoc", "http://www.aade.gr/myDATA/invoice/v1.0");
//Example to get the root element
XmlNodeList root = xml.SelectNodes("/InvoicesDoc:InvoicesDoc", manager);
//Example to get the VatNumber tag
XmlNodeList aNodes =xml.SelectNodes("/InvoicesDoc:InvoicesDoc/InvoicesDoc:invoice/InvoicesDoc:issuer/InvoicesDoc:vatNumber", manager);
Modify XML existing content in C#
Well, If you want to update a node in XML, the XmlDocument
is fine - you needn't use XmlTextWriter
.
XmlDocument doc = new XmlDocument();
doc.Load("D:\\build.xml");
XmlNode root = doc.DocumentElement;
XmlNode myNode = root.SelectSingleNode("descendant::books");
myNode.Value = "blabla";
doc.Save("D:\\build.xml");
C# : Modify a xml node
Try this:
xml.SelectSingleNode("//reminder/Title").InnerText = "NewValue";
Your foreach
line is simply looping through a list of elements called "reminders", not it's child nodes.
Take a look at this xpath tutorial for more information:
http://www.w3schools.com/xpath/xpath_intro.asp
How to update node values in XML using C#
Got it!
public static void ReplaceCode()
{
var root = new XmlDocument();
root.Load(@"C:\data.xml");
foreach (XmlNode e in root.GetElementsByTagName("alternateID"))
{
if (e.Attributes["code"].Value.Equals("ALT"))
{
e.FirstChild.Value = "00000000"; // FirstChild because the inner node is actually the inner text, yeah XmlNode is weird.
break;
}
}
root.Save(@"C:\data.xml");
}
Ask me anything about it and I can clarify. :)
Edit xml file using xmldocument, search by attribute
This should work for you. Your main node already contains element Game - that's why you won't be able to find it in ChildNode. I corrected your main path not to include Game node. So now, you can find it in ChildNodes collection. I added some checks for Node.Name and Attribute name to be sure that it is Game node. It should work for you.
XmlNode node = xdoc["Data"]["Place"]["Date"];
int countvalues = 100;
for (int i = 0; i < countvalues; i++)
{
foreach (XmlNode childNode in node.ChildNodes)
{
if (childNode.Name == "Game" && childNode.Attributes["Name"].InnerText.Equals("Tennis"))
{
childNode["balance"].InnerText = xBal.Text;
}
}
}
How to change the value of an element in an xml file?
Use LINQ and XDocument
:
string applicationName = "Test";
XDocument xdocument = XDocument.Load("Data.xml");
var appName = xdocument.Elements("applicationName").Single();
appName.Value = applicationName;
xdocument.Save("Data.xml");
But you should add System.Xml.Linq
to your using directives first.
Related Topics
Find Methods That Have Custom Attribute Using Reflection
When Using a Settings.Settings File in .Net, Where Is the Config Actually Stored
Read Appsettings JSON Values in .Net Core Test Project
Using Webclient in C# How to Get the Url of a Site After Being Redirected
Connect to Active Directory via Ldap
How to Get a List<String> Collection of Values from App.Config in Wpf
How to Get Byte Array Properly from an Web API Method in C#
Get Substring - Everything Before Certain Char
How to Use a Dataadapter with Stored Procedure and Parameter
Learning Single Responsibility Principle with C#
How to Extend C# Built-In Types, Like String
Are Protected Members/Fields Really That Bad
How to Make a Combobox Non-Editable in .Net
How to Fix Wpf Error: "Program Does Not Contain a Static 'Main' Method Suitable for an Entry Point"