none
Add XElement to another XElement in specific location RRS feed

  • Question

  • My XML

    <Bank>  
     <Customer id="0">  
      <Accounts>  
       <Account id="0" />  
       <Account id="1" />                        
      </Accounts>  
     </Customer>  
      <Customer id="2">  
      <Accounts>  
       <Account id="0" />                      
      </Accounts>  
     </Customer>  
    </Bank>

    i want to add  new account element before customer id=2.
    i have this xml in xelement and i want to add other xelement to the first. how can do that?
    Thanks for the help.

    Friday, February 7, 2020 10:26 AM

All replies

  • Check one of possibilities to add <Customer id=‘1’/> (in C#):

    using System.Xml.XPath;

    . . .

    XDocument xdoc = XDocument.Load( @"C:\MyFile1.xml" );

     

    XElement el = xdoc.XPathSelectElement( "/Bank/Customer[@id='2']" );

    if( el != null )

    {

       XElement new_el = new XElement( "Customer", new XAttribute( "id", 1 ) );

       el.AddBeforeSelf( new_el );

    }

     

    // if you want to save it:

    xdoc.Save( @"C:\MyFile2.xml" );

    Friday, February 7, 2020 8:18 PM