1

I want to add a node named list under product node.

code in xaml is:

<Window.Resources>
    <XmlDataProvider x:Name="myDP" x:Key="MyData" Source="Product.xml" XPath="products" 
                     IsAsynchronous="False" IsInitialLoadEnabled="True"
                     PresentationTraceSources.TraceLevel="High">
    </XmlDataProvider>
</Window.Resources>

the addIdtm_button is:

 private void addItem_Click_1(object sender, RoutedEventArgs e)
 {
     try
     {
         XmlDataProvider provider = (XmlDataProvider)this.FindResource("MyData");
         XmlNode elmnt = provider.Document.CreateElement("item");
         elmnt.InnerText = itemTextBox.Text;

         provider.Document.ChildNodes[0].AppendChild(elmnt);
     }
     catch (Exception d)
     {
         MessageBox.Show(d.Message);
     }
 }

When button is clicked, the MessageBox is displayed: "The current node cannot contain other nodes."

what can I do now???

Abhishek
  • 2,925
  • 4
  • 34
  • 59
miltan
  • 1
  • 3

1 Answers1

0

You are appending to the first child of the document. provider.Document.ChildNodes[0] will return XmlDeclaration, Value="version=\"1.0\" encoding=\"utf-8\". So instead use provider.Document.ChildNodes[1] which will return products node.

After modifying your code your addItem_Click_1 looks like this:

private void addItem_Click_1(object sender, RoutedEventArgs e)
{
    try
    {
        XmlDataProvider provider = (XmlDataProvider)this.FindResource("MyData");
        XmlNode elmnt = provider.Document.CreateElement("list");
        elmnt.InnerText = itemTextBox.Text;            
        (provider.Document.ChildNodes[1]).ChildNodes[0].AppendChild(elmnt);
        // Assuming that your XML file is in the same directory as you exe. If not, then 
        // give the right path as parameter to Save
        provider.Document.Save("Product.xml");
    }
    catch (Exception d)
    {
        MessageBox.Show(d.Message);
    }
}

In the above code, provider.Document.ChildNodes[1] will return products node from the XML file. (provider.Document.ChildNodes[1]).ChildNodes[0] will return product node to which you should AppendChild

Abhishek
  • 2,925
  • 4
  • 34
  • 59