c#linq到xml:根据值将子元素添加到特定的父元素 [英] c# linq to xml: add child element to specific parent element based upon value

查看:124
本文介绍了c#linq到xml:根据值将子元素添加到特定的父元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用LINQ to XML在c#中制作XML配置文件编辑器.在插入具有特定父值的子节点时,我遇到了困难.

I'm making an XML configuration file editor in c# by means of LINQ to XML. I have run into difficulty inserting child nodes where specific parent values are present.

我现在的代码:

var xdoc = XElement.Load(config.ConfigPath);
....
xdoc.Descendants("grandparent")
.Where(a => a.Element("parent")
.Value == "targetvalue").FirstOrDefault()
.Add(new XElement("grandchild", grandchildvalue));  

产量:

<grandparent>
     <parent>
     <grandchild>

而不是预期的:

<grandparent>
     <parent>
          <grandchild>

在代码的这一点上,仅创建了祖父母节点和父节点,并且正在创建孙元素及其相应值.如何使孙子元素从属于父元素?

At this particular point in the code, only the grandparent and parent nodes have been created, and the grandchild element is being created along with its respective value. How do I make the grandchild element subordinate to the parent element?

在此先感谢您的帮助.

Thank you in advance for any assistance.

推荐答案

感谢您的回复.修改为以下内容后,您的回复确实会产生正确的结果

Thank you for the response. Your response does produce the correct result, when modified to:

 xdoc.Descendants("grandparent")
    .Descendants("parent")
    .Where(a => a.Attribute("name").Value == parentvalue).FirstOrDefault()                                                                            
    .Add(new XElement("grandchild", grandchildvalue));

事实证明,我以前的xml结构是错误的.在给父节点一个值而不是一个属性时,我得到的输出如下:

As it turns out, my previous xml structure was wrong. In giving the parent node a value rather than an attribute, I was getting output like:

<parent>parentvalue</parent><grandchild>grandchildvalue</grandchild>

它们在同一级别上.通过属性设置父级的值,可以将孙子级的值设置为从属于父级的值.感谢您帮助我发现这个愚蠢的初学者的错误!

where they were on the same level. Setting the parent's value via an attribute allowed for the grandchild's value to be set as subordinate to the parent's. Thank you for helping me to find this silly beginner's mistake!

这篇关于c#linq到xml:根据值将子元素添加到特定的父元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆