使用 XDocument 添加属性时出现问题
请注意最后一条评论:OP 只是忘记调用 Save()
。
我正在检查 ProductDetails 节点下属性 ProductCount 的 XML,如果该属性不存在,则在此节点下添加具有默认值的属性。
我可以检查该属性是否存在,但无法添加它,尽管它没有给我任何错误,但甚至没有添加该属性。
这是我的代码:
XDocument XMLDoc = XDocument.Load(fileName);
foreach (var detail in XMLDoc.Descendants(_ns + "ProductDetails"))
{
if (detail.Attribute("ProductCount") == null)
{
detail.SetAttributeValue("ProductCount", "1");
}
}
_ns 有我的命名空间。
我无法弄清楚我做错了什么,如果 ProductCount 属性不存在,为什么它不添加它。
Please note the very last comment: The OP just forgot to call Save()
.
I am checking XML for attribute ProductCount under ProductDetails node, and if the attribute is not present add the attribute with a default value under this node.
I am able to check if the attribute exists or not but I am not able to add it, though it does not give me any error but does not even add the attribiute.
here is my code:
XDocument XMLDoc = XDocument.Load(fileName);
foreach (var detail in XMLDoc.Descendants(_ns + "ProductDetails"))
{
if (detail.Attribute("ProductCount") == null)
{
detail.SetAttributeValue("ProductCount", "1");
}
}
_ns has my namespace.
I am not able to figure out what I am doing wrong, why is it not adding ProductCount attribute if it does not exist.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试将值作为整数而不是字符串传递,如下所示:
编辑:写了不好的建议...但我尝试测试你的问题...
创建了一个.xml文件,内容为:
测试代码:
结果b.xml文件内容:
所以一切都对我有用。
Try to pass value as integer instead of string like this:
EDIT: wrote bad suggestion...but I tried to test your problem...
created a.xml file with content:
test code:
and result b.xml file content:
So everything is working for me.
试试这个:
Try this: