将现有的 XML 子值更改为 textbox.text

Change existing XML child value with textbox.text

我一直在尝试将 TextBox.Text 值应用到我现有的 XML 文件节点,我尝试了很多方法,但似乎没有成功。

我的代码:

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);

   }

}

我的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>

有谁知道将 TextBox.Text 添加到现有子节点的最佳方法吗?

elList 变量是 null,因为你忘记了 XPath 中的 root 节点。如果只有一个 filter_item 节点,正如我从您对 SelectSingleNode 的使用推测的那样,这应该有效:

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);

这将产生以下 XML 文档:

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