Question

How to copy an xml section with a different name?
For example I have:

  <R id="r4" Name="r 4">
    <P>
      <Pr id="p3e3" />
      <Pr id="p3e4" />
    </P>
  </R>

And I want to copy it, but with a different name and id, for example:

  <R id="copy4" Name="copy 4">
    <P>
      <Pr id="p3e3" />
      <Pr id="p3e4" />
    </P>
  </R> 

I am getting the existing part using:

    IEnumerable<XElement> r = null;

    r =
        from el in myxml.Root.Elements()
        where el.Attribute("id").Value == myvalue
        select el;

And then I copy it by:

    myxml.Descendants("S").FirstOrDefault().Add(
        new XElement("R", new XAttribute("id", GetRandomId()), new XAttribute("Name", "Copyof" + myvalue), 
        ??????? ->how do I copy the content?
Was it helpful?

Solution

I think you want

myxml.Descendants("S").FirstOrDefault().Add(
    new XElement("R", new XAttribute("id", GetRandomId()), new XAttribute("Name", "Copyof" + myvalue), 
    r.First().Nodes())

if you want to copy the contents of the first item in r or

myxml.Descendants("S").FirstOrDefault().Add(
    new XElement("R", new XAttribute("id", GetRandomId()), new XAttribute("Name", "Copyof" + myvalue), 
    r.Nodes())

if you want to copy the contents of all items in r.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top