简体   繁体   English

选择XML元素的值

[英]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. 我对XML文件没有太多的经验,但是我试图附加一个我在网上找到的教程来满足我的需求,但并没有得到我期望的结果。

https://support.microsoft.com/en-us/help/307548/how-to-read-xml-from-a-file-by-using-visual-c https://support.microsoft.com/zh-CN/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: 我的XML在大多数情况下看起来像这样:

<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 我试图用每个状态的值填充列表框,但是我的代码要么返回空白,要么仅返回XML标记内的文本

eg State.. State.. repeated for each element. 例如State .. State ..对每个元素重复。

          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" reader.Name返回“状态” reader.Value返回“空白”

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? 我不明白为什么reader.Value不返回肯塔基州KY ...我已经看到了其他使用字符串生成器的示例,这是一个不好的方法吗?

Try xml linq : 试试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: 您可以使用XmDocument(请参阅: https ://msdn.microsoft.com/zh-cn/library/system.xml.xmldocument( v= vs.110).aspx),然后使用xpath表达式从中获取正确的元素您的文件:

Also it is better to encapsulate the name of the state (that is, if you own the xml document) like this: 同样,最好像这样封装状态名称(即,如果您拥有xml文档):

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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