Click here to Skip to main content
15,888,088 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
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:
XML
<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 :

VB
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

Not sure, what you want to achieve, but take a look at below code:
VB.NET
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!
 
Share this answer
 

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900