简体   繁体   中英

Selecting the value of XML elements

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

eg 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?

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

使用reader.ReadString()而不是reader.Value

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM