使用XDocument添加属性时出现问题 [英] problem adding attribute using XDocument
问题描述
我正在检查XML的ProductDetails节点下的属性ProductCount,如果该属性不存在,请在该节点下添加具有默认值的属性.
我可以检查该属性是否存在,但是我无法添加该属性,尽管它不会给我任何错误,但是甚至不会添加属性.
这是我的代码:
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");
}
}
<productdetails hadsuspension="false" iscomplimentary="false" hasfamily1="false" hasfamily2="false" isinsured="false" hasjoint="false" />
_ns有我的命名空间
我无法弄清楚我在做什么错,如果它不存在,为什么不添加ProductCount属性.
_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.
推荐答案
SetAtttribute
不会为XElement
创建新属性.只会更改指定属性的值.
您可以尝试以这种方式创建-
Hi,
SetAtttribute
won´t create a new attribute for theXElement
. It will just change the value of the specified attribute.
You can try creating this way -
detail.Add(new XAttribute("ProductCount", 1));
上面将为细节XElement创建一个新的ProductCount属性.添加新属性后,还应该保存xml.
希望这会有所帮助.
编辑-BobJanova是正确的,SetAttributeValye确实创建了一个新属性.
The above will create a new ProductCount attribute for the detail XElement. You should also save the xml after you add the new attribute.
Hope this helps.
Edit - BobJanova is right, SetAttributeValye does create a new attribute.
这篇关于使用XDocument添加属性时出现问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!