Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

copy all xml attributes from 1 node to another

Tags:

c#

xml

hi I have 2 xml nodes and I need to copy only all the attributes from the first into the other `

 XmlDocument doc = new XmlDocument();
XmlDocument doc1 = new XmlDocument();
doc.Load(somepath);
XmlNode node=doc.CreateNode(System.Xml.XmlNodeType.Element, "something", null);
System.Xml.XmlNodeList list = doc.GetElementsByTagName("tananana");
XmlNode node1= list[0];
Foreach (XmlAttribute att in node1.Attributes)
{
     System.Xml.XmlAttribute rAtt= doc.CreateAttribute(att.name ); //att.name is problem
     rAtt.Value=att.Value;  //att.value is problem
     node1.Attributes.Add(rAtt);
 }

Input test.xml:

<data>
  <tananana a1="1" a2="2"/>
  <tananana a3="3" a4="5"/>
  <tananana a1="5" a2="7"/>
</data>

Output:

<data>
  <something a1="1" a2="2" />
  <something a3="3" a4="5" />
  <something a1="5" a2="7" />
</data>
like image 735
Sonja Avatar asked Apr 25 '17 12:04

Sonja


Video Answer


2 Answers

Input test.xml:

<data>
  <tananana a1="1" a2="2"/>
  <tananana a3="3" a4="5"/>
  <tananana a1="5" a2="7"/>
</data>

Output:

<data>
  <something a1="1" a2="2" />
  <something a3="3" a4="5" />
  <something a1="5" a2="7" />
</data>

Code:

namespace StackOverflow
{
    using System.IO;
    using System.Linq;
    using System.Xml.Linq;

    class Program
    {
        static void Main(string[] args)
        {
            var doc1 = XDocument.Load("test.xml");
            var doc2 = new XDocument(new XElement(doc1.Root.Name));

            doc2.Root.Add(doc1.Root
                .Elements("tananana")
                .Select(x => new XElement("something", x.Attributes())));
        }
    }
}
like image 74
Szer Avatar answered Oct 03 '22 07:10

Szer


If you want to use XmlDocument then this would work.
SetAttribute() copies value if an attribute exists in dstNode and creates new attribute otherwise

    protected void CopyAllAttributesValues(XmlElement srcNode, XmlElement dstNode)
    {
        foreach (XmlAttribute att in srcNode.Attributes)
        {
            dstNode.SetAttribute(att.LocalName, att.Value);
        }
    }
like image 29
Sylwester Santorowski Avatar answered Oct 03 '22 06:10

Sylwester Santorowski