简体   繁体   English

从XML读取属性

[英]Reading Attributes from XML

What I'm trying to do is read some data from an xml file and assign the data to a label when the user clicks on an item in a listbox. 我想做的是从xml文件中读取一些数据,并在用户单击列表框中的项目时将数据分配给标签。 This is the code I have tried, the code compiles but nothing happens to my label. 这是我尝试过的代码,可以编译,但标签没有任何反应。

private void lbAllModules_SelectedIndexChanged(object sender, EventArgs e)
    {
        XmlTextReader inforeader = new XmlTextReader(workingDir + @"\modules.xml");


        while (inforeader.Read())
        {
            if ((inforeader.NodeType == XmlNodeType.Element) && (inforeader.Name == "modulecode"))
            {

                if (inforeader.HasAttributes)
                {
                    lblCodeOut.Text = inforeader.GetAttribute(0);
                }


            }

        }
    }

If you want to use LINQ to XML: 如果要使用LINQ to XML:

XDocument loaded = XDocument.Load(@"C:\modules.xml");

 // Query the data for first attribute of element 'modecode'
var q = from c in loaded.Descendants("modulecode")
        where c.HasAttributes
        select (string)c.Attributes().FirstOrDefault();

foreach (var item in q)
{
     Console.WriteLine(item);    
}

Be sure your node is called exactly "modulecode". 确保您的节点被精确地称为“模块代码”。 Comparison is case-sensitive. 比较是区分大小写的。 You can use 您可以使用

string.Compare(inforeader.Name,"modulecode", StringComparison.OrdinalIgnoreCase) == 0; 

for case-insensitive comparison. 用于不区分大小写的比较。 Then try 然后尝试

if(inforeader.MoveToFirstAttribute())
   lblCodeOut.Text = inforeader.Value;

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

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