这是我的代码我从xml文件到列表框中获取了所有数据,唯一缺少的是属性我试图让属性显示有些困难。不确定究竟要做什么或我缺少什么。我之前从未做过xml。
string startPath = Application.StartupPath + "\\ContactManager.xml";
XmlTextReader textReader = new XmlTextReader(startPath);
string Names = "";
string sex = "";
while (textReader.Read())
{
switch (textReader.NodeType)
{
case XmlNodeType.Attribute:
sex = textReader.GetAttribute("Sex");
break;
case XmlNodeType.Element:
Names = textReader.Name;
break;
case XmlNodeType.Text:
Console.WriteLine();
lbDisplay.Items.Add(sex + Names + ": " + textReader.Value);
break;
}
}
这些是xml文件中的一些元素Sex
是属性。
<Contact Sex="M">
<FirstName>Mickey</FirstName>
<LastName>Mouse</LastName>
<PhoneNumber>401-555-1212</PhoneNumber>
<FaxNumber>401-666-6666</FaxNumber>
<EmailAddress>mmouse@disney.com</EmailAddress>
</Contact>
答案 0 :(得分:2)
您需要将代码更改为:
string startPath = Application.StartupPath + "\\ContactManager.xml";
XmlTextReader textReader = new XmlTextReader(startPath);
string Names = "";
string sex = "";
while (textReader.Read())
{
switch (textReader.NodeType)
{
case XmlNodeType.Element:
Names = textReader.Name;
if(textReader.Name == "Contact") sex = textReader.GetAttribute("Sex");
break;
case XmlNodeType.Text:
Console.WriteLine();
lbDisplay.Items.Add(sex + Names + ": " + textReader.Value);
break;
}
}