Jaro
Jaro

Reputation: 1754

Duplicate existing element in xml in C#

Please I would like to clone element prijemkaItem from this xml:

enter image description here

The element prijemkaItem is got by this function:

XElement doc = XElement.Load("input.xml");            
        XmlReader reader = XmlReader.Create("input.xml");

        while (reader.Read())
        {
            switch (reader.NodeType)
            {
                case XmlNodeType.Element:

                    if (reader.Name == "pri:prijemkaItem")
                        elementPrijemkaItem = XElement.ReadFrom(reader) as XElement;

                    break;
            }
        }
        reader.Close()

I would like to put this element behind itself. Please any idea, how can I do this?

Thanks for any advice.

Upvotes: 1

Views: 2035

Answers (1)

Omar
Omar

Reputation: 16623

Assuming for simplicity that your Xml structure is the following:

<?xml version="1.0" encoding="utf-8"?>
<dat:dataPack xmlns:dat="datNamespace">
  <dat:dataPackItem>
    <pri:prijemka xmlns:pri="priNamespace">
      <othernode></othernode>
    </pri:prijemka>
  </dat:dataPackItem>
</dat:dataPack>

If you want to duplicate the pri:prijemka node you can use Linq to Xml:

//using System.Xml.Linq;

//load the xml file
Document doc = XDocument.Load( "D:\\input.xml" );
//get the "dat" namespace 
var datNamespace = doc.Root.GetNamespaceOfPrefix( "dat" );

//get "dat:dataPackItem" node
var dataPackItemNode = doc.Root.Element( datNamespace + "dataPackItem" );
//since you don't know the "pri" namespace you can do:
var prijemkaNode = dataPackItemNode.Descendants( )
                       .Where(x => x.Name.LocalName == "prijemka")
                       .FirstOrDefault();

//add it to the "dat:dataPackItem" node
dataPackItemNode.Add( prijemkaNode );
//save the xml file
doc.Save( "D:\\input.xml" );   

The result is:

<?xml version="1.0" encoding="utf-8"?>
<dat:dataPack xmlns:dat="datNamespace">
  <dat:dataPackItem>
    <pri:prijemka xmlns:pri="priNamespace">
      <othernode></othernode>
    </pri:prijemka>
    <pri:prijemka xmlns:pri="priNamespace">
      <othernode></othernode>
    </pri:prijemka>
  </dat:dataPackItem>
</dat:dataPack>

Upvotes: 1

Related Questions