Edit specific Element in XDocument
With using System.Xml.Linq;
it becomes
var doc = XElement.Load(fileName);
var saveGame = doc
.Element("savegames")
.Elements("savegame")
.Where(e => e.Element("IdNumber").Value == "2")
.Single();
saveGame.Element("balance").Value = "50";
doc.Save(fileName);
Update Specific value of specific XML tag using XDocument
Use XDocument
to parse the xml string. Find the money XElement
and update his value.
public void Button1_Click(object sender, EventArgs e)
{
XDocument doc = XDocument.Load(@"XMLFile1.xml");
var result = doc.Root.Descendants("money").FirstOrDefault();
if (result == null)
return;
result.Value = txt.Text;
doc.Save(@"XMLFile1.xml");
}
EDIT
Check dotNetFiddle
How to update all instances of an element in XDocument?
Linq is a query language, so you can't directly use it to modify the value, but you can easily select all the Resource
elements in the document with it and iterate/change them.
For example:
// or load from xml, however you have it
var xDoc = XDocument.Load(@"c:\temp\myxml.xml");
// iterate every Resource element
foreach (XElement element in xDoc.Descendants("Resource"))
element.Value = "Hello, world";
That will pick out every Resource
element in the XML regardless of where it is in the hierarchy, which in your case, is what you need. If you needed to target it more specifically, you could either use an XPath expression or further Linq calls such as Element()
which work on a single level of the hierarchy.
Edit existing element in XDocument
Method DescendantsAndSelf(XName name)
returns every element that has matching name and all descendant elements of this element (MSDN). In your case that's body
element with its children.
You probably want to form your XML like the following one:
<?xml version="1.0" encoding="UTF-8"?>
<body>
<someElement>
<id>1</id>
<disc>B</disc>
<type>Mark</type>
<value>5</value>
</someElement>
<someElement>
<id>2</id>
<disc>A</disc>
<type>Mark</type>
<value>10</value>
</someElement>
</body>
so you can get single someElement
XML node like this:
var target = doc.DescendantsAndSelf("someElement")
.Where(e => e.Element("disc").Value == Disc
&& e.Element("type").Value.ToString().Equals(Type.ToString())
&& e.Element("value").Value.ToString().Equals(OldMark.ToString()))
.Single();
Debug.WriteLine(target.ToString());
Get Element from XDocument & Edit Attribute
You can try this way :
XNamespace ns = "http://fake.com/services";
XElement xmlPromotionElement = xmlPromotionResponse.Descendants(ns+"Promotion")
.SingleOrDefault();
xmlPromotionElement.Attribute("PromotionId").Value = "XXX";
Use simple XNamespace
+ local-name to reference an element in namespace. Then you can use .Attribute()
method to get XAttribute
from an XElement
and change the attribute's value.
How to modify a specific XElement into a file.xml
So for updating all Banana's Color to YELLOW use this code:
string xmlFilePath = @"C:\Users\codroipomad\Desktop\slave\Test.xml";
XDocument xdoc = XDocument.Load(xmlFilePath);
XNamespace ns = "http://www.fruitauthority.fake";
var elBanana = xdoc.Descendants()?.Elements(ns + "FruitName")?.Where(x => x.Value == "Banana")?.Ancestors(ns + "Fruit");
foreach (var item in elBanana)
{
var elColor = item.Elements(ns + "FruitColor").FirstOrDefault();
//check se il file esiste,se non esiste lo crea
if (!File.Exists(xmlFilePath))
File.Create(xmlFilePath).Dispose();
if (elColor != null)
{
elColor.Value = "YELLOW";
}
}
xdoc.Save(xmlFilePath);
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
Post String to ASP.NET Web API Application - Returns Null
How to Programmatically Change Printer Settings with the Webbrowser Control
How Does C# Choose with Ambiguity and Params
Convert String to Decimal, Keeping Fractions
What's the Max Items in a List<T>
Differencebetween .Equals and ==
Making a Web Request to a Web Page Which Requires Windows Authentication
Why Does a Bad Password Cause "Padding Is Invalid and Cannot Be Removed"
Quartz.Net Setup in an ASP.NET Website
Thread Safety of a Dictionary<Tkey, Tvalue>
Programmatic Way to Get All the Available Languages (In Satellite Assemblies)
Get the Name of a Method Using an Expression
C# Linq Intersect/Except with One Part of Object
How to Get Current User Who's Accessing an ASP.NET Application
An Expression Tree Lambda May Not Contain a Null Propagating Operator
Why Is Parallel.Foreach Much Faster Then Asparallel().Forall() Even Though Msdn Suggests Otherwise