简体   繁体   中英

c# xml linq add element to an element

i've been searching and trying for hours but i can't make it work. so i decided to ask a question here. kindly help me.

i have an xml something like this

<parent>
    <anothertag/>
    <body>
        <monitor value="3"/>
        <mouse value="5"/>
        <chair>
            <monoblock value="5"/>
        </chair>
    </body>
</parent>

and this is my desired xml output if possible

<parent>
    <anothertag/>
    <body>
        <anotherbody>
            <monitor value="3"/>
            <mouse value="5"/>
            <chair>
                <monoblock value="5"/>
            </chair>
        </anotherbody>
    </body>
</parent>

this is my code

string xml = "<parent>" +
                "<anothertag/>" +
                "<body>" +
                "<monitor value=\"3\"/>" +
                "<mouse value=\"5\"/>" +
                "<chair>" +
                "<monoblock value=\"5\"/>" +
                "</chair>" +
                "</body>" +
                "</parent>";
                XDocument doc = XDocument.Parse(xml);
                var p = doc.Descendants("body").Elements();

                foreach (var item in doc.Descendants("body").ToList())
                {
                    item.Add(new XElement("anotherbody", p));
                }

                Console.WriteLine(doc.ToString());

and here is the output

    <parent>
  <anothertag />
  <body>
    <monitor value="3" />
    <mouse value="5" />
    <chair>
      <monoblock value="5" />
    </chair>
    <anotherbody>
      <monitor value="3" />
      <mouse value="5" />
      <chair>
        <monoblock value="5" />
      </chair>
    </anotherbody>
  </body>
</parent>

the output is redundant. how do i remove it?

the p.Remove(); remove all the elements. thank you

Try this

foreach (var item in doc.Descendants("body").ToList())
{
      item.ReplaceAll(new XElement("anotherbody", item.Nodes()));
}

I think the problem is that in this line

 var p = doc.Descendants("body").Elements();

you should not be extracting the .Elements() from your descendants. Change the line to

var p = doc.Descendants("body");

and it should work. But keep in mind that .Descendants() will find all of the tags that match the name specified even if they are nested inside other tags.

This may be ok if the tag <body> only appears as a child of <parent> , if not it would be better to rewrite the line in question as follows

var p = doc.Elements("body");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM