• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 429
  • Last Modified:

Add XML Nodes to an existing Doc.

I have a base XML document with multiple nodes.  I need to clone the layout for an existing node and multiple it in a foreach loop.  

 

How do I add in multiple nodes for each arrest?  
<Arrests>
<Arrest>

      <CaseNumber></CaseNumber>

      <ArrestedOn></ArrestedOn>

      <ChargeClass></ChargeClass>

      <ChargeDescription></ChargeDescription>

      <Sentenced></Sentenced>

      <DaysInJail></DaysInJail>

      <DisposedOn></DisposedOn>

      <DispositionCode></DispositionCode>

      <DispositionDescription></DispositionDescription>
</Arrest>
</Arrrests>
 

For some customers I have a number around 40, for others only 1-2-3  :)

I am trying this but I am missing the basic point.

XmlNodeList aIns = Node.SelectNodes("/Person/Arrests");

 XmlNode NewNode = aIns[0].Clone();          

 
what am I doing wrong?

TIA

 
0
srussell705
Asked:
srussell705
  • 2
1 Solution
 
Fernando SotoRetiredCommented:
What version of the .Net Framework are you using
Visual Studio 2003 = .Net 1.1
Visual Studio 2005 = .Net 2.0
Visual Studio 2008 = .Net 3.5
0
 
Fernando SotoRetiredCommented:
Hi srussell705;

The following code snippet will work in the .Net 2.0 and above, VS 2005 and VS 2008.

Fernando
XmlDocument doc = new XmlDocument();
doc.Load("Test.xml");

// Setup the inner text for each node to update the data
List<string> fieldsValues = new List<string>() {"2", DateTime.Now.AddDays(-10).ToShortDateString(), "1",
    "B&E","1 year", "1 year", DateTime.Now.ToShortDateString(), "0", "Complete"};
// Reference to the root node
XmlNode root = doc.SelectSingleNode("//Arrests");
// Clone first arrest to create the arrest node and all its children
XmlNode arrest = doc.SelectSingleNode("//Arrests/Arrest").Clone();
// Update the cloned nodes
int idx = 0;
foreach (XmlNode n in arrest.ChildNodes)
{
    n.InnerText = fieldsValues[idx];
    idx++;
}
// Attach the new Arrest node to the end of all its children
root.AppendChild(arrest);
// Save the new document
doc.Save("TestNew.xml");

Open in new window

0
 
srussell705Author Commented:
Thanks.  Worked like a charm.  

I missed the whole List idea for the stuffing.  
0

Featured Post

Hire Technology Freelancers with Gigs

Work with freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely, and get projects done right.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now