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>
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())));
}
}
}
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With