0

I'm curious how you can display a specific node content in a textbox

My XML file:

<?xml version="1.0"?>
<root>
  <debug_mode>true</debug_mode>
  <filter>
    <filter_item>1158</filter_item>
    <filter_item>1159</filter_item>
    <filter_item>1160</filter_item>
  </filter>
</root>

My cs file:

 public MainWindow()
        {
            InitializeComponent();

            XmlDocument Xdoc = new XmlDocument();

            Xdoc.Load(xmldoc);
            XmlElement el = (XmlElement)Xdoc.SelectSingleNode("root/filter/filter_item");         
            tbOrderDisplay.Text = el.InnerText;

        }

Innertext sadly doesn't display anything in my textbox, is there a way to apply a foreach to show every item? (I'm still learning how to work with c#)

  • 1
    IMO, you should better start with `System.Xml.Linq` instead of `System.Xml`. See e.g. [XDocument or XmlDocument](https://stackoverflow.com/q/1542073/1136211). – Clemens Nov 17 '20 at 14:36
  • But how do I pick out a node? Because I want to display the content of a childnode in my textbox and with xdocument there is no option to select a single node –  Nov 17 '20 at 14:44
  • Read the documentation. Something like Enumerable.First or FirstOrDefault should work. – Clemens Nov 17 '20 at 14:46
  • So I read throught the documentation, but it's mainly explaining on how to create a document when my xml file that's included already exists. The only thing I'm supposed to do is to pick up node values and display them in my textbox. Now I found out that you can pick them up by using root.element referring to the value, but how do I eventually link this to my textbox.text? –  Nov 17 '20 at 15:04
  • `tbOrderDisplay.Text = string.Join(",", Xdoc.SelectNodes("root/filter/filter_item").Cast().Select(x => x.InnerText.Trim()));` this works, you can change the separator as needed, I was going to add an answer, but Clemens already mentions a good example. – Trevor Nov 17 '20 at 15:28
  • Thank you non the less, I appreciate the effort ! –  Nov 18 '20 at 09:25

1 Answers1

0

Something like this should work:

var root = XDocument.Load(xmldoc).Root;
var filter = root.Element("filter");

foreach (var filterItem in filter.Descendants("filter_item"))
{
    tbOrderDisplay.Text += filterItem.Value + "\n";
}

Or shorter:

tbOrderDisplay.Text = string.Join("\n",
    filter.Descendants("filter_item").Select(f => f.Value));
Clemens
  • 123,504
  • 12
  • 155
  • 268