[英]Adding attributes to xelements of existing xml
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. 当我在调试模式下检查节点的值时,我看到它们全部具有open属性。 However, when I check the value of gridxml, the elements don't have the open attribute.
但是,当我检查gridxml的值时,元素没有open属性。 What am I doing wrong?
我究竟做错了什么?
gridxml
in you example is a String
which you are never modifying. 您的示例中的
gridxml
是一个您从未修改过的String
。 XDocument
is not an XML-friendly String
wrapper, it is a separate object, which has no influence over the String
it was initialized from. XDocument
不是XML友好的String
包装器,它是一个单独的对象,它对其初始化的String
没有影响。
You should be checking xdoc.ToString()
instead of gridxml
. 您应该检查
xdoc.ToString()
而不是gridxml
。 If for some reason you need to have the updated contents in your original variable, do gridxml = xdoc.ToString()
after adding the attributes. 如果由于某种原因需要在原始变量中包含更新的内容,请在添加属性后执行
gridxml = xdoc.ToString()
。
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());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.