0

I don't have much experience with XML files but I'm trying to append a tutorial I found online to suite my needs and I'm not getting the results I would expect.

https://support.microsoft.com/en-us/help/307548/how-to-read-xml-from-a-file-by-using-visual-c

I've searched around but everything I've found doesn't make sense to me.

My XML looks like this for the most part:

<US>
    <!-- Kentucky Start -->
    <State>Kentucky KY
        <City>Newport
            <Street>Pavilion Parkway<Number>130<PostalCode>41071</PostalCode></Number></Street>
        </City>
        <City>Corbin
            <Street>Highway 90<Number>7351<PostalCode>40701</PostalCode></Number></Street>
        </City>
    </State>
</US>

I'm trying to populate a listbox with the value of each state but my code either returns white space or just the text within the XML tag

e.g. State.. State.. repeated for each element.

          while (reader.Read()) {
                switch (reader.NodeType) {

                    case XmlNodeType.Element: // The node is an element.

                        // Skip over root element
                        if (reader.Name.Equals("US")) {

                            reader.MoveToNextAttribute();

                        }
                        else {

                            if(reader.Name.Equals("State")) {
                                lbState.Items.Add(reader.Name);
                                lbState.Items.Add(reader.Value);
                            }

                        }
                        break;

reader.Name returns "State" reader.Value returns "Whitespace"

I don't understand why reader.Value does not return Kentucky KY... I've seen other examples that use string builder, is this a bad approach?

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
shockemc
  • 85
  • 1
  • 10
  • 1
    Is there any reason you really need to use `XmlReader`? It's a relatively low-level API which works well if you need to stream an *enormous* document, but it's normally much simpler to load the whole document into memory with LINQ to XML (`XDocument` etc) – Jon Skeet Nov 28 '17 at 07:31
  • I would try to avoid the `XmlReader` the API is not really friendly... – royalTS Nov 28 '17 at 07:32
  • There is no particular reason. As I mentioned earlier, I have very little to almost no experience with XML or reading in XML files in. I was simply able to get the tutorial posted working in a console app and went with it. Do you have a recommendation? I'd greatly appreciate it. – shockemc Nov 28 '17 at 07:43
  • Just stumbled on this, https://stackoverflow.com/questions/642293/how-do-i-read-and-parse-an-xml-file-in-c I think this may be what I was looking for. – shockemc Nov 28 '17 at 07:55

3 Answers3

1

Try xml linq :

sing System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication2
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(FILENAME);

            var results = doc.Descendants("State").Select(x => new {
                cities = x.Elements("City").Select(y => new {
                    state = (string)x,
                    city = (string)y,
                    streets = y.Elements("Street").Select(z => (string)z).ToList()
                }).ToList()
            }).SelectMany(x => x.cities).ToList();
        }
    }
}
jdweng
  • 33,250
  • 2
  • 15
  • 20
1

Use reader.ReadString() instead of reader.Value

Sunil
  • 3,404
  • 10
  • 23
  • 31
  • Worked like a charm, Thank you. I'll probably use one of the other answers but technically this answered my question as it was asked. – shockemc Nov 28 '17 at 08:42
  • 1
    I would suggest you to stick to XmlReader due to it's high performance with large Xml. (It's like a SAX parser, fast and forward only) – Sunil Nov 28 '17 at 08:45
1

You can use XmDocument (see: https://msdn.microsoft.com/en-us/library/system.xml.xmldocument(v=vs.110).aspx) and then use an xpath expression to get the right elements from your document:

Also it is better to encapsulate the name of the state (that is, if you own the xml document) like this:

<name>Kentucy KY</name>

So you can do the following:

var items = new List<string>();

XmlDocument xmlDocument = new XmlDocument();
xmlDocument.LoadXml("yourxml");
var xmlNodes = xmlDocument.SelectNodes("//State/Name");
foreach (XmlNode node in xmlNodes)
{
    items.Add(xmlNode.Value);
}