简体   繁体   中英

copy all xml attributes from 1 node to another

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);
        }
    }

Beside copying name and value, you should also consider what happens if an attribute is prefixed with a namespace, which the other answers so far would miss. Therefor just use the CloneNode method, instead copying 'manually'.

XmlAttribute newAttribute = (XmlAttribute)sourceAttribute.CloneNode(true);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM