Modify Xml Existing Content in C#

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");

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");

Modifying Existing XML Content in C#

From MSDN: "An XPathNavigator object is created from a class that implements the IXPathNavigable interface such as the XPathDocument and XmlDocument classes. XPathNavigator objects created by XPathDocument objects are read-only while XPathNavigator objects created by XmlDocument objects can be edited. An XPathNavigator object's read-only or editable status is determined using the CanEdit property of the XPathNavigator class."

So, first of all you have to use XmlDocument, not XPathDocument, if you want to set an attribute.

An example of how to modify XML data using an XPathNavigator using the CreateNavigator method of an XmlDocument, is shown here.

As you'll see from the example, there is a method SetValue on your it.Current object.

Here's how you would do it for your code, with some slight modifications:

        int vid = 2;
var doc = new XmlDocument();
doc.LoadXml("<Equipment><Items><SubItems vid=\"1\" name=\"Foo\"/><SubItems vid=\"2\" name=\"Bar\"/></Items></Equipment>");
var nav = doc.CreateNavigator();

foreach (XPathNavigator it in nav.Select("/Equipment/Items/SubItems"))
{
if(it.MoveToAttribute("vid", it.NamespaceURI)) {
int vidFromXML = int.Parse(it.Value);
if (vidFromXML == vid)
{
// if(it.MoveToNextAttribute() ... or be more explicit like the following:

if (it.MoveToParent() && it.MoveToAttribute("name", it.NamespaceURI))
{
it.SetValue("Two");
} else {
throw new XmlException("The name attribute was not found.");
}
}
} else {
throw new XmlException("The vid attribute was not found.");
}
}

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);

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.

What's the best way to update xml in a file?

By design, XmlReader represents a "read-only forward-only" view of the document and cannot be used to update the content. Using the Load method of either XmlDocument, XDocument or XElement, will still cause the entire file to be read in to memory. (Under the hood, XDocument and XElement still use an XmlReader.) However, you can combine using a raw XmlReader and XElement together using the overloads of the Load method which take an XmlReader.

You don't describe your XML structure, but you would want to do something similar to this:

var reader = XmlReader.Create(@"file://c:\test.xml");  
var document = XElement.Load(reader);
document.Add(new XElement("branch", "leaves"));
document.Save("Tree.xml");

To find a specific node (for example, with a specific attribute value), you'd want to do something similar to this:

var node = document.Descendants("branch")
.SingleOrDefault(e => (string)e.Attribute("name") == "foo");

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



Related Topics



Leave a reply



Submit