-2

I've been trying for days to read a value from XML file into a text box. I searched relevant questions:

Reading values from xml file with Linq
C# Reading from XML files
Getting values from xml file using C#
How to Read values from XML file
and videos:
https://www.youtube.com/watch?v=4dPWkEARptI
https://www.youtube.com/watch?v=-DwANN5_BoE

Still, I couldn't correctly read the "Background" value and always get this Error: (I doubt it has to do with hierarchy of the XML file and I'm not choosing the correct Element \ Node) What did I miss?

An unhandled exception of type 'System.Xml.XmlException' occurred in System.Xml.dll
Additional information: 'None' is an invalid XmlNodeType. 

My XML file:

<?xml version="1.0"?>
<ArrayOfXMLSaveClass xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">

  <XMLSaveClass>

    <Background>D:\Temp\100 Ideas for Every Occasion.pdf</Background>

</XMLSaveClass>

My code so far:

        private void button4_Click(object sender, EventArgs e)
        {
            OpenFileDialog OP = new OpenFileDialog();
            OP.Filter = "XML files (*.xml)|*.xml";
            OP.DefaultExt = "xml";
            OP.AddExtension = true;
            if (OP.ShowDialog() == DialogResult.OK)
            {
                XmlReader XDoc = XmlReader.Create(OP.Filename);

                while (XDoc.Read());
                {
                    if (XDoc.NodeType == XmlNodeType.Element && XDoc.Name == "Background")
                    {

                    }                   
                } 
                string L01 = XDoc.ReadElementString();
                txtInputFileT.Text = L01;   
            }
        }
5
  • 1
    To begin with, the XML snippet you've posted is incomplete. Commented Feb 24, 2021 at 9:38
  • @aybe could you please elaborate ? Commented Feb 24, 2021 at 9:39
  • It's not "incomplete", it's invalid XML. Commented Feb 24, 2021 at 9:40
  • @IanKemp which line is invalid ? Commented Feb 24, 2021 at 9:42
  • 3
    the tag ArrayOfXMLSaveClass has no closing tag. Anyway why do you parse the xml yourself node by node? Why not use linq2Xml or an XmlSerializer? Commented Feb 24, 2021 at 9:43

1 Answer 1

1

What about the following, it does read and print all Background descendants ?

using System;
using System.IO;
using System.Xml.Linq;

namespace zzzzzzzz
{
    internal static class Program
    {
        private static void Main(string[] args)
        {
            var xml = @"<?xml version=""1.0""?>
<ArrayOfXMLSaveClass xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">
  <XMLSaveClass>
    <Background>D:\Temp\100 Ideas for Every Occasion.pdf</Background>
  </XMLSaveClass>
</ArrayOfXMLSaveClass>
";

            using var reader = new StringReader(xml);

            var xDocument = XDocument.Load(reader);

            var xElements = xDocument.Descendants("Background");

            foreach (var element in xElements)
            {
                Console.WriteLine($"{element.Name}: {element.Value}");
            }
        }
    }
}

enter image description here

Edit:

This works, by the way, your XML wasn't valid, here's a correct one:

enter image description here

Code:

using System;
using System.Windows.Forms;
using System.Xml;

namespace WinFormsApp1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            var dialog = new OpenFileDialog
            {
                Filter = "XML (*.xml)|*.xml"
            };

            if (dialog.ShowDialog() != DialogResult.OK)
                return;

            using var stream = dialog.OpenFile();
            using var reader = XmlReader.Create(stream);

            while (reader.Read())
            {
                if (reader.NodeType != XmlNodeType.Element || reader.Name != "Background")
                    continue;

                var value = reader.ReadElementContentAsString();

                MessageBox.Show(value);
            }
        }
    }
}

XML:

<?xml version="1.0" encoding="utf-8"?>

<ArrayOfXMLSaveClass xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <XMLSaveClass>
        <Background>D:\Temp\100 Ideas for Every Occasion.pdf</Background>
    </XMLSaveClass>
</ArrayOfXMLSaveClass>
Sign up to request clarification or add additional context in comments.

3 Comments

the code in my question, worked in some of the example videos, however it does not on my end. Could you pin point the cause? Much appreciate it.
works perfectly with only 1 line in XML file. When I add more Elements it gives an error and goes to line 59 which the last line in he file The ReadElementContentAsString method is not supported on node type None. Line 59, position 23.
use XDocument, it's much better

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.