This is my code:
var nodes = XDocument.Parse(gridxml).Root.Elements();
var attribute = new XAttribute("open", "0");
foreach (var node in nodes)
{
node.Add(attribute);
}
When I check the value of the nodes in debug mode, I see that all of them have the open attribute. However, when I check the value of gridxml, the elements don't have the open attribute. What am I doing wrong?
gridxml
in you example is a String
which you are never modifying. XDocument
is not an XML-friendly String
wrapper, it is a separate object, which has no influence over the String
it was initialized from.
You should be checking xdoc.ToString()
instead of gridxml
. If for some reason you need to have the updated contents in your original variable, do gridxml = xdoc.ToString()
after adding the attributes.
You are adding attributes to copies of the nodes, try this:
string gridxml = "<node1><node2></node2><node3></node3></node1>";
var xdoc = XDocument.Parse(gridxml);
var attribute = new XAttribute("open", "0");
foreach (var node in xdoc.Root.Elements())
{
node.Add(attribute);
}
Console.WriteLine(xdoc.ToString());
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.