对类似问题的回答对我没有帮助;或者我错过了一些非常明显的东西。
我想在 XML 结构<value>
的<question>
元素中添加一个元素,如下所示:
<form>
<foo>
<bar>
<question id="1">...</question>
<question id="2">...</question>
</bar>
</foo>
</form>
其他问题似乎侧重于将元素添加到根元素中,但我正在尝试根据属性值将我的元素进一步添加到树中。我尝试了以下不起作用的方法:
XDocument newFormTemplateXML = XDocument.Load("newFormTemplate.xml");
XElement newValue = new XElement("value", 123);
newFormTemplateXML
.Descendants()
.Where(d => d.Name.ToString().Equals("question") && d.Attribute("id").Equals(1))
.Append(newValue);
newFormTemplateXML.Save("test.xml");
我没有收到错误消息。有人可以帮助我走上正确的道路吗?
使用“本地”方法:
newFormTemplateXML
.Descendants("question")
.Single(q => (int) q.Attribute("id") == 1)
.Add(newValue);
或者,对于 XPath 爱好者:
newFormTemplateXML.XPathSelectElement("//question[@id=1]").Add(newValue);
请注意,这并不能验证实际上只有一个带有id
1 的问题,它只会修改第一个这样的问题。该Single()
调用不存在这个问题/优势。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句