Based on your code and description. I create a sample , and it works well. So I think maybe you didn't call the Save Method to save the document. After we add a node, we should call the Save Method to save the change. So I would like to suggest you to check
your code and call the Save Method.
Here is what I did:
XDocument document = XDocument.Load(@"..\..\XMLFile1.xml");
//XElement newnode = new XElement("DatiOrdineAcquisto","new Element");
document.Element("FatturaElettronicaBody").Element("DatiGenerali").Element("DatiGeneraliDocumento").AddAfterSelf(new XElement("DatiOrdineAcquisto", "New Element"));
document.Save(@"..\..\XMLFile1.xml");
Console.WriteLine("OK");
Console.ReadKey();
None
0 Points
2 Posts
Add a node after a specific node with linq2xml
Jun 28, 2014 05:47 AM|rpisani|LINK
I have this XML file:
...
<FatturaElettronicaBody>
<DatiGenerali>
<DatiGeneraliDocumento>
...
</DatiGeneraliDocumento>
</DatiGenerali>
</FatturaElettronicaBody>
I need to insert a new node <DatiOrdineAcquisto> at runtime after the node <DatiGeneraliDocumento>.
I tried this code:
FatturaPA.Element("FatturaElettronicaBody").Element("DatiGenerali").Element("DatiGeneraliDocumento").AddAfterSelf(New XElement("DatiOrdineAcquisto"))
but it doesn't work.
What can I do?
Thanks.
<div style="color: blue; font-weight: normal; margin-left: -4em;" xmlns="http://www.w3.org/1999/xhtml"></div>
Participant
890 Points
160 Posts
Re: Add a node after a specific node with linq2xml
Jun 30, 2014 03:51 AM|Luther.Lv|LINK
Hi rpisani,
Based on your code and description. I create a sample , and it works well. So I think maybe you didn't call the Save Method to save the document. After we add a node, we should call the Save Method to save the change. So I would like to suggest you to check your code and call the Save Method.
Here is what I did:
Xml file:
Hope it can helps you.
Best Regards.
None
0 Points
2 Posts
Re: Add a node after a specific node with linq2xml
Jul 04, 2014 10:30 AM|rpisani|LINK
Thanks Luther.
I work in VB and I rewrote your code in this way:
and it seems to work.
But my problem is this:
My XML file is similar to the following:
<FatturaElettronicaBody>
<DatiGenerali>
...
<ImportoDocumento>1000,00</ImportoDocumento>
</DatiGenerali>
</FatturaElettronicaBody>
I need to insert one or more block as at:
<DatiOrdineAcquisto>
<RiferimentoNumeroLinea>1</RiferimentoNumeroLinea>
<IdDocumento>1</IdDocumento>
...
</DatiOrdineAcquisto>
at Runtime after <ImportoDocumento> using Linq2Xml and VB.
Also I should insert other bloks like <DatiOrdineAcquisto> it it exists otherwise after <IdDocumento>.
Can you help me?
Thanks.