Click here to Skip to main content
14,486,704 members
Rate this:
Please Sign up or sign in to vote.
See more:
I have an xml file that I am building. I am trying to copy/clone (whatever you want to call it) one element to the end. Here is a quick view:
<VDZ>
  <Transformer>
    <Tx>
      <Handle>1</Handle>
      <ID>TBA</ID>
      <Rating>200kVA</Rating>
      <Z>0.03444</Z>
      <Points>
        <P ID="0" X="120" Y="96" />
      </Points>
    </Tx>
  </Transformer>
</VDZ>


I am using a LINQ query to get the element based on the Handle Element, like such :

Dim query = (From p In xml_Proj.Descendants()
                            Where p.Element("Handle") = ActiveHandle
                            Select p).FirstOrDefault


So I have query, but how do I clone/copy it? I need to know it came from the Transformer element and I want to add another one at the end. I have tried using the below but I am getting null.
Dim root As XElement = query.Parent


How can I get the name of the descendant and place a copy of the element under it? Thanks.

What I have tried:

I have tried as mentioned above
Posted
Updated 22-Mar-20 3:14am
Comments
Maciej Los 22-Mar-20 8:57am
   
What exactly do you want to copy? Tx or Transformer node?
Please, provide example output.

1 solution

Rate this:
Please Sign up or sign in to vote.

Solution 1

Not sure, what you want to achieve, but take a look at below code:
Dim xcontent As String  = "<VDZ>
  <Transformer>
    <Tx>
      <Handle>1</Handle>
      <ID>TBA</ID>
      <Rating>200kVA</Rating>
      <Z>0.03444</Z>
      <Points>
        <P ID='0' X='120' Y='96' />
      </Points>
    </Tx>
  </Transformer>
</VDZ>"

Dim xdoc AS XDocument = XDocument.Parse(xcontent)
Dim secondTransformer As XElement = New XElement(xdoc.Descendants("Transformer").FirstOrDefault())
Dim h As XElement = secondTransformer.Descendants("Handle").FirstOrDefault()
h.Value = 2
xdoc.Root.Add(secondTransformer)
'new node hase been added!
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100