Change existing XML child value with textbox.text

297 views Asked by At

I've been trying to apply TextBox.Text values to my existing XML file nodes, I've tried many ways but it doesn't seem to pick up on it.

My code:

private void btnAddId_Click(object sender, RoutedEventArgs e)
{

   if (tbAddId.Text == "")
   {
      MessageBox.Show("No value was given!");
   }
   else if (tbAddId.Text == "Add ID")
   {
      MessageBox.Show("No value was given!");
   }
   else
   {
      XmlDocument Xdoc = new XmlDocument();
      string xmldoc = (@"// path to my xml file");
      Xdoc.Load(xmldoc);


      XmlElement elList = (XmlElement)Xdoc.SelectSingleNode("/filter/filter_item");

      if (elList != null)
      {
         XmlNode node = Xdoc.SelectSingleNode("filter_item");
         node.InnerText = tbAddId.Text;
         elList.AppendChild(node);
      }

      Xdoc.Save(xmldoc);

   }

}

My xml:

<?xml version="1.0"?>
<root>
  <filter>
    <!-- Copy filter-item and put the order-id in as the value to skip it-->
    <filter_item>
    </filter_item>
  </filter>
</root>

Does anyone know the best way to add TextBox.Text to an existing child node?

1

There are 1 answers

0
thatguy On BEST ANSWER

The elList variable is null, because you forgot the root node in the XPath. If there is only one filter_item node, as I guess from your usage of SelectSingleNode, this should work:

XmlDocument Xdoc = new XmlDocument();
string xmldoc = (@"// path to my xml file");
Xdoc.Load(xmldoc);


var filterItemNode = Xdoc.SelectSingleNode("root/filter/filter_item");
if (filterItemNode != null)
   filterItemNode.InnerText = tbAddId.Text;

Xdoc.Save(xmldoc);

This will result in the following XML document:

<?xml version="1.0"?>
<root>
   <filter>
      <filter_item>Text from the TextBox</filter_item>
   </filter>
</root>